Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: dependencies reference nonexistent parent node for an installed app
I'm using a third party Django app (github link) in my project and trying to create a one-to-one field reference to one of its models. Organization = saas.models.Organization # Saas is my installed app class OrganizationProfile(TimeStampedModel): # TimeStampedModel is imported from django_extensions.db.models organization = models.OneToOneField(Organization, on_delete=models.CASCADE, related_name='profile') display_name = fields.CharField(max_length=127) # other fields When I make the migrations, there are two files generated 0013_auto_20200415_1919.py in the site-packages directory of my venv saas/migrations/0013_auto_20200415_1924.py 0001_initial.py in my own application where I've defined this one-to-one relationship. This file has a dependency to ('saas', '0013_auto_20200415_1924') which as expect has ForeignKey relation defined for profiles Now I've two questions, Why is the first file created? (here's the content of the first file for reference) How do I export this first file into a new environment as it is present in my site-packages and not part of VCS Because of this, I get the following error when I apply migration in my production environment Migration 0001_initial dependencies reference nonexistent parent node ('saas', '0013_auto_20200415_1924') I feel like I'm making some silly mistake, but not able to figure out what. -
Can't display MySQL data in html using Django
My code works fine and nothing is wrong, did not get any errors. But, what is weird is that I have id, name, email, major in mysql "students" table. but I don't see anything in my html page. what to do? stuck at this point. any suggestions? models.py class Students(models.Model): id = models.IntegerField(unique=True, primary_key=True) name = models.CharField(max_length=255) email = models.CharField(max_length=255) major = models.CharField(max_length=255) class Meta: managed = False db_table = 'students' views.py def showStudents(request): result = Students.objects.all() return render(request, 'students.html', {'results': result}) students.html {% extends 'base.html' %} {% block content %} {% for student in results %} <table> <tr> <th>ID</th> <th>Name</th> <th>Email</th> <th>Major</th> </tr> <tr> <td>{{ student.id }}</td> <td>{{ student.name }}</td> <td>{{ student.email }}</td> <td>{{ student.major }}</td> </tr> </table> {% endfor %} {% endblock %} urls.py urlpatterns = [ path('admin/', admin.site.urls), path('students', showStudents, name='students'), ] -
Free web hosts based on linux for Django? [closed]
I have been creating web apps for quite a while and have deployed many of them on Heroku. Most people do not prefer heroku due to the fact that going production level is really expensive. Same goes for pythonanywhere. Are there any other good, free web hosting services that is preferably based on linux? I don't really want to spend money on deploying websites yet since I have zero experience on deploying on such servers. I did try out AWS but my credit card does not work for international purpose. -
Django Different User Types Impelementation
Building a multiple different level, also with different permissions user types in Django models, how should it be implemented? I have one example here and I'm not sure as for the permissions, if this would be the best model, since I know there are a few variations and would like to know if I'm doing it right. class UserProfile(models.Model): user = models.ForeignKey(User) #define general fields class Agent(models.Model): profile = models.ForeignKey(UserProfile) #agent specific fields class Meta: db_table = 'agent' class Management(models.Model): profile = models.ForeignKey(UserProfile) #customer specific fields class Meta: db_table = 'management' class Contractor(models.Model): profile = models.ForeignKey(UserProfile) #customer specific fields class Meta: db_table = 'contractor' I'm actually looking for 4 User Type accounts: Agent, Customer, Management, Contractor. How to implement this in Django, both different permissions and fields? -
why does not django create db_index for object_id for GenericForeignkey?
i am using django 2.2. i have create a like/dislikie system using generic relation. django only create a indexing for contenttype but not object_id. if i try to count likes/dislike for specific model with specific object id it will be slow because there is no indexing for object_id. if my generic model is connected to 10 models where each models has many objects and each objects has many likes. here counting number of likes/dislike will be slow because it will use indexing for contenttype only. -
Putting tags in a StructBlock
I want to be able to add tagging to a custom StructBlock that I've created. The current model looks like this class MapsIndicatorBlock(blocks.StructBlock): text_icon = blocks.CharBlock( label='Maps/Indicators Text or Icon', required=False ) pop_up_title = blocks.CharBlock( label='Pop-Up Title', required=False ) pop_up_text = blocks.RichTextBlock( label ='Pop-Up Text/Image', required=False ) pop_up_colour = blocks.CharBlock( choices=constants.BOOTSTRAP4_BUTTON_COLOUR_CHOICES, default='btn btn-primary', max_length=128, required=False ) tags = TaggableManager() objects = models.Manager() class Meta: template = 'cityregiontable/map_indicator_block.html' The TaggableManager() was designed to be used with models.model not blocks.StructBlock. I have tried to create a way to create the tags using the following to no avail. I get the error RE: not being able to find the model for MapsIndicatorBlock. This is correct as MapsIndicatorBlock is a block, not a model. class MITag(TaggedItemBase): content_object = models.ForeignKey( 'MapsIndicatorBlock', on_delete=models.CASCADE, related_name='tagged_mi_block' ) How can I allow -
how to customize login url and condition in django simple jwt
I have an app with multi user type, Author, Moderator and Manager. this groups have different android apps. and I've used django simple JWT token for login. the problem is that Author can login in moderator app and moderator can login in others app and so on. the question is that, how can i separate login urls and conditions for these groups?? -
Whats the meaning of 5 at the end of manytomany in views in django?
I'm working with many to many databases in Django but I do not understand one piece of code. what's the meaning of 5 in the below line of code: areadata.objects.get(id = area_id).pub.add(mymodel.objects.get(id = restaurant_id),5) If anyone knows that meaning please explain to me. -
How to make a python script which automatically execute after a certain time django
I am making a website with django in which user need to upload a text file it will be saved with its named appended with the time of upload, I want to write a python script which deletes the file from the media folder after a certain time(e.g. one day after the upload time) how to do so and in which file or folder should I code this part to make it work properly -
Order queryset by a certain key value
I want to show items with a certain foreign key first. Tried this, but it doesn't seem to work: class Part(models.Model): press = models.ManyToManyField(Press) class Order(models.Model): press = models.ForeignKey(Press) class PartListView(ListView): def get_queryset(self): qs = Part.objects.all().order_by('-pk') press = None if 'pk' in self.kwargs: order_id = self.kwargs['pk'] order = Order.objects.get(id=order_id) press = order.press # Get the foreign key value if press is not None: qs = sorted(qs, key=lambda Part: Part.press == press) return qs -
starting new django project [duplicate]
I am a beginner and self learning django. So i have this question If I have already installed django and virtualenv once then is it necessary that i have to do it again and again if i have to start a new project? every time i watch a tutorial in youtube they always install django and setup virtual env. I mean at first you might need but after you did it once,is it necessary to do it again and agian? Please don't make fun of me I am just confused! -
In django, how to get all data with exact foreign key? example, get all posts with foreign key = 1 or 2 or
from django.db import models from django.contrib.auth.models import User from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=200) content = models.TextField() date_posted = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User, on_delete=models.CASCADE) def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) Hello im new to django and this is my model and I have 2 tables "auth_user" table and "blog_post" table. Inside blog_post table I have a column called "author_id" which is the foreign key between "blog_post" table and "auth_user" table. The question is how can i get all posts from "blog_post" table when foreign key = 1 or 2 or 3 or.. etc. Thanks before hand. -
retriever data from python file and using it in js
I have this in my views.py: import json import requests def geojsonFun(request): r = requests.get('http://localhost:8000/villeLis/') data = r.json() geojson = { "type": "FeatureCollection", "features": [ { "type": "Feature", "geometry": { "type": "Point", "coordinates": [d["coordonate_x"], d["coordonate_y"]], }, "properties": d, } for d in data] } # print(geojson) return HttpResponse(geojson) I used serializers to have the json file from my mysql database and the link is working, the problem i am not able to see my points on the map on my dashboard.html here is a part of it: var geojson = geojson; mapboxgl.accessToken = 'pk.eyJ1IjoieW9zcmFqYWJyaSIsImEiOiJjazh4M3duc3AwMnJhM2VzMmxjOThxa2F6In0.OAugyooi_oKgzRTznR4eyw'; var map = new mapboxgl.Map({ container: 'map', style: 'mapbox://styles/mapbox/streets-v11', center: [9.5, 36.5], zoom: 7 }); map.addSource(currentKey, { "type": "geojson", "data": geojson, cluster: true }); map.addLayer({ id: 'points', source: 'pointsSource', type: 'circle',}); I want retrive the result of the function in python and use it as geojson in the js. -
Django Rest Framework - AttributeError: Got AttributeError when attempting
I am new to the Django Rest Framework and I try to build an API that lets a user create projects. That means the user - authenticated via a knox token - should become the owner of the created project instance. However, I am getting the following error, when doing a POST-request to /api/project/: AttributeError: Got AttributeError when attempting to get a value for field `username` on serializer `UserSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `ManyRelatedManager` instance. Original exception text was: 'ManyRelatedManager' object has no attribute 'username'. urls.py: urlpatterns = [ path('api/projects/', ProjectListCreate.as_view()), path('api/project/', ProjectCreate.as_view()), path('api/project/<int:pk>', ProjectDetailShow.as_view()) ] api.py: class ProjectListCreate(generics.ListAPIView): queryset = Project.objects.all() serializer_class = ProjectSerializer class ProjectDetailShow(generics.RetrieveUpdateDestroyAPIView): queryset = Project.objects.all() serializer_class = ProjectDetailSerializer permission_classes = [IsOwnerOrReadOnly] class ProjectCreate(generics.CreateAPIView): serializer_class = ProjectDetailSerializer permission_classes = [permissions.IsAuthenticated] def perform_create(self, serializer): serializer.save(owner=self.request.user) serializer.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email') class ProjectSerializer(serializers.ModelSerializer): owner = UserSerializer(read_only=True) class Meta: model = Project fields = ('id', 'name', 'owner', 'mission', 'category', 'status') class ProjectDetailSerializer(serializers.ModelSerializer): owner = UserSerializer(read_only=True) participants = UserSerializer(read_only=True) class Meta: model = Project fields = ('id', 'name', 'owner', 'participants', 'mission', 'category', 'description', 'status') models.py: class Project(models.Model): STATUS_CHOICES = (...) … -
Can I access to request object in django @register.assignment_tag
I need to access request object in a custom html tag (Django ver 1.11). This tag is used in a top level html template which is used by almost all other templates in the proyect. My code is this: @register.assignment_tag(takes_context=True) def get_color_style(context): request = context.get('request', None) #<---Here request object is None try: color = ehealth_models.CssSkin.objects.get( clinic=get_current_clinic(request) ).color_scheme except (ehealth_models.CssSkin.DoesNotExist, ValueError): color = 'defaultcolor' less_rule = os.path.join( settings.BASE_DIR, static('less/' + color + '.less')[1:] ) color_values = dict() with open(less_rule, 'r') as f: file_str = f.read() file_str = file_str.replace('\n', '') for item in next(csv.reader([file_str], delimiter=';')): rule_item = next(csv.reader([item], delimiter=':')) if len(rule_item) == 2: color, color_value = None, None for value in rule_item: value = value.replace(' ', '') if value.startswith('@'): color = value.replace('@', '').replace('-', '_') elif value.startswith('#'): color_value = value color_values[color] = color_value return color_values Any idea? Thanks! -
Hashing file within DRF (POST HTTP request)
I'm creating a REST API and I'm not particularly savvy in Django. I'd like to post an uploaded file, but before doing so I'd like to create the sha256 of the file, like so: def sha256sum(filename): h = hashlib.sha256() b = bytearray(128*1024) mv = memoryview(b) with open(filename, 'rb', buffering=0) as f: for n in iter(lambda : f.readinto(mv), 0): h.update(mv[:n]) return h.hexdigest() In order for this to work, I require the actual file (or file path), and not the actual filename. My code in my viewsets.py: def create(self, request): serializer = FileSerializer(data=request.data) f = request.FILES["file"] # just gives the filename print(request.META) if serializer.is_valid(): f = serializer.save() print(f"f: {f}") res_name = sha256sum(f) print(f"res_name: {res_name}") return Response(serializer.data, status=status.HTTP_201_CREATED) Any ideas where I am going wrong? -
Starting monitor thread on django
Let me give a bit of context. I'm currently building a simple web page in which, by filling out a form and hitting send, a recon of a target website is ran. The idea is to monitor this targets that I have already scanned. My idea was to make some requests to my database and check which targets have not been found in the last week (if target not scanned in past week, run scan again) For doing this, I was trying to start a thread which, once a day, checks which targets need to be scanned again. The problem is that for doing this, I need to time.sleep my thread for 24 hours, this should not be an issue, but it seems that runserver is being delayed by this sleep time. Here is my monitor method which will be assigned to a thread def start_monitor(): while 1: today = dt.datetime.now() targets = mongo.get_targets() for target in targets: target_last_date = mongo.get_target_last_scan(target) date_diff = target_last_date - today if date_diff.days > 7: print('Running recon again') else: print('Not yet') wait_to_tomorrow() return The thread starts with monitor_thread = threading.Thread(name='Monitor Process', target=monitor.start_monitor()) monitor_thread.setDaemon(True) monitor_thread.start() Where should I start the thread? -
Python Django: You're using the staticfiles app without having set the STATIC_ROOT setting setting to a filesystem path
i am trying to deploy my site using heroku but when i run git push heroku master it shows: remote : raise ImproperlyConfigured("You're using the staticfiles app " remote : django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. remote: remote : ! Error while running '$ python manage.py collectstatic --noinput'. settings.py import django_heroku import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '*******************************' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'users.apps.UsersConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'pytalk.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'pytalk.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': … -
Adding custom user authentication to django-rest-framework-simple-jwt
I want to add user login via One-time Password as well as the usual username/password method in django. In order to do so, either username/password or username/OTP are sent from client to sever and based on the provided pair of fields, I need to return access and refresh token if the user is authenticated. I am using django's simple-jwt. I know that I have to override TokenObtainPairView and TokenObtainSerializer. The problem is, I want to do the field validation part myself. In my views, I override simple-jwt's default view. #views.py class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer And I override the serializer like below: #serializers.py class MyTokenObtainPairSerializer(TokenObtainPairSerializer): def validate(self, attrs): try: request = self.context["request"] except KeyError: pass try: request_data = json.loads(request.body) if("username" in request_data and "password" in request_data): # default scenario in simple-jwt pass elif("username" in request_data and "otp" in request_data): # validate username/otp manually and return access/token pair if successful pass else: # some fields were missing raise serializers.ValidationError({"username/otp or username/password" : "These fields are required"}) except: pass So, if client passes user credentials in the forms below, I will be able to authenticate it and return token pair. { "username" : "Winston", "password" : "testpass" } or { "username" : … -
Django REST Framework: NestedSerializer in OneToMany relation
I have 2 related models: class Systems(models.Model): name = models.CharField(max_length=200) description = models.CharField(max_length=2000, null=True, blank=True) class Teams(models.Model): system = models.ForeignKey(Systems, on_delete=models.CASCADE) name = models.CharField(max_length=200) description = models.CharField(max_length=2000, null=True, blank=True) And 2 serializers: class System_serializer(serializers.HyperlinkedModelSerializer): id = serializers.ReadOnlyField class Meta: model = Systems fields = ('id', 'name', 'description') def create(self, validated_data): return Systems.objects.create(**validated_data) def update(self, system, validated_data): system.name = validated_data.get('name', system.name) system.description = validated_data.get('description', system.description) system.save() return system second: class Team_serializer(serializers.ModelSerializer): id = serializers.ReadOnlyField system_id = System_serializer() class Meta: model = Teams fields = ('id', 'system_id', 'name', 'description') def create(self, validated_data): return Teams.objects.create(**validated_data) def update(self, team, validated_data): team.name = validated_data.get('name', team.name) team.description = validated_data.get('description', team.description) team.save() return team In 'team' entity I just want to have only 'System' ID, not the whole 'System' How can I use the System_serializer, to serialize 'system_id' in 'team' object? Thanks! -
Django channels deploy - error during handshake
I deployed a Django application to a VPS, everything seems to work except for the Django Channels part of the app. I'm trying to establish a connection from a template to my websocket consumer, but i keep getting the following error: (index):10 WebSocket connection to 'ws://mydomain/receiver' failed: Error during WebSocket handshake: Unexpected response code: 404 Here is how i deployed the app: /etc/nginx/sites-available/myproject server { listen 80; server_name 54.39.20.155; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /WaitingRoomVenv/WaitingRoom/WaitingRoom/static; } location / { include proxy_params; proxy_pass http://unix:/WaitingRoomVenv/WaitingRoomEnv.sock; } } /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=root Group=www-data WorkingDirectory=/WaitingRoomVenv/WaitingRoom ExecStart=/WaitingRoomVenv/WaitingRoomEnv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/WaitingRoomVenv/WaitingRoomEnv.sock WR.wsgi:application [Install] WantedBy=multi-user.target And here is the Daphne service: [Unit] Description=daphne service to run Channels on WaitingRoom After=network.target After=nginx.service [Service] Type=simple RuntimeDirectory=daphne PIDFile=/run/daphne/pid User=root Group=www-data WorkingDirectory=/WaitingRoomVenv/WaitingRoom ExecStart=/WaitingRoomVenv/WaitingRoomEnv/bin/daphne -u /tmp/daphne.sock WR.asgi:application ExecStop=/WaitingRoomVenv/WaitingRoomEnv/bin/kill -s TERM $MAINPID [Install] WantedBy=multi-user.target Both these two services are running without any erros, but when i try to run Channels on any template, i get the error. Can anyone help me find what am i doing wrong? -
How to create video synchronous web app with Node.js?
I want to create a web app similar to GAZE. It's a video synchronous web app. Is node.js is good for building this web app? If yes then what library should I use? If no then which technology I should use? -
how to make calculations within loop in html table (django)
i have table in html: ab=[24,56,78] <table > <tr><th>ab</th> {% for d in ab %} <td>{{ d }}</td> {% endfor %} </tr> </table> ab is a list. How i can automatically multiple list ab by 100 within loop ? -
Python csv reader for row in reader - what does the the throwaway underscore represent in this code?
I'm reading data from a csv file. I get that 'row' is the variable that represents the loop I am going through, but what is the "_" that is being thrown away here? for row in csv_reader: _, Student.objects.get_or_create( first_name=row[0], last_name=row[1], email=row[2], organisation=row[3], enrolled=row[4], last_booking=row[5], credits_total=row[6], credits_balance=row[7], ) -
How do you view your PostgreSQL database and tables that are part of a Django app that has been uploaded to Heroku?
Built a Django app locally. Worked fine. Uploaded to Heroku which appeared to be successful. However "user" table is evidently corrupted. I cannot login or create users without errors on Django app on Heroku. I want to modify (specifically delete) rows in the "user" table of the PostgreSQL database on Heroku. How can I do that? I ran the following from the CLI without success: heroku run python manage.py makemigrations heroku run python manage.py migrate