Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
N+1 queries in SerializerMethodField
I have this view def get_queryset(self) -> QuerySet[Good]: .... qs = ( Good.objects.values('brand_id', 'brand__name') .annotate( .... ) .prefetch_related(Prefetch('history', StocksHistory.objects.filter(Q(**subquery_filter_args)))) .order_by('-total_sales') ) return qs and serializer class ExtendedBrandSerializer(serializers.ModelSerializer): ... history = serializers.SerializerMethodField() class Meta: model = Good fields = ( ... 'history', ) def get_history(self, good: dict) -> dict: .... return StocksHistorySerializer( StocksHistory.objects.extra(select={'day': 'date( snap_at )'}) .values('day') .filter(history_filter_query) .annotate( .... ), many=True, ).data Relation: StocksHistory (*) -> (1) Good. I have N+1 queries in SerializerMethodField. How can I fix it? Perhaps there is a way to move annotate from serializer to view? The bottom line is that I also need the history key in the response, which will contain a list of these child objects. -
django is there a send_mass_mail() limit?
So, im using the send_mass_mail() function from django.core.mail module. I want to know if there is any limiting in the amount of recipients, and mails. -
Django djoser jwt auth can you add fields to jwt token payload data?
I am using django with djoser and django rest framework simple jwt for authentication, can i add fields (for example: user role, user name) to the jwt payload data? -
Django Form initial value for image field
I have a user model with username, and an imagefield. And a django form with the same fields. When user wants to edit his profile i want to populate the existing values so user doesn't have to enter them all. I tried using initial = {"username": user.username, "image": user.image} form = Form(initial=initial) Then I render the form using form.as_p in a template. Username is okay but image doesn't show. Is there any way to do it? -
How can I fix this AttributeError?('AnonymousUser' object has no attribute '_meta')
I am trying to extend User model using OneToOneField. forms.py: class UserForm(forms.ModelForm): class Meta: model = User fields = ('username', 'first_name', 'last_name', 'password1', 'password2') class EmployerForm(forms.ModelForm): class Meta: model = Employer fields = '__all__' views.py: def update_profile(request): if request.method == 'POST': user_form = UserForm(request.POST, instance=request.user) employer_form = EmployerForm(request.POST, instance=request.user.employer) if user_form.is_valid() and employer_form.is_valid(): user_form.save() employer_form.save() else: user_form = UserForm(instance=request.user) employer_form = EmployerForm(instance=request.user.employer) return render(request, 'employer.html', { 'user_form': user_form, 'employer_form': employer_form }) html: <form method="post"> {% csrf_token %} {{ user_form.as_p }} {{ employer_form.as_p }} <button type="submit">Save changes</button> </form> this is the AttributeError: 'AnonymousUser' object has no attribute '_meta' How can I fix it? -
Django REST get "application/x-www-form-urlencoded" and return "application/xml"
I'm writing integration with payments gateway and I have problem with sending response to provider. They are sending request with data in "application/x-www-form-urlencoded" form and are expection. Thats their request headers: {'Content-Length': '917', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'Accept': 'application/xml', 'User-Agent': 'Apache-HttpClient/4.5.13 (Java/11.0.15)', 'Accept-Encoding': 'gzip,deflate', 'Host': '89.xxxxxxxx', 'Via': '1.1 payxxxxxx (squid/3.5.20)', 'X-Forwarded-For': '10.xxxxxx', 'Cache-Control': 'max-age=259200', 'Connection': 'keep-alive'} I don't know how to use two renderer classes in django - one for taking request and one for responding. I was trying to add parser_classes = (XMLParser,) but then it shows me error 415 as response (Unsupported Media Type). Rn I'm getting 406 - (Not Acceptable) - {"detail":"Could not satisfy the request Accept header."} Payment gateway is sending POST request. My attempt for handling it was: class ITNView(APIView): #parser_classes = (XMLParser, JSONParser) def post(self, request): body = request.data['transaction'] #form-encoded print(body) print(request.headers) return Response(request.data, content_type="application/xml") but this doesn't work. Have you an idea how can I handle application/x-www-form-urlencoded as request data and respond with XML? -
Automatic add Users to another class after authorization and how to avoid issues after changing field's names of old data
I'm using standard django.contrib.auth.models User. And I have some registered users. I want to create a class Member: class Member(models.Model): id_user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="ninja") And want to relate new users with the class Member automatically. I have several questions. How can I relate the classes automatically after authorization? How can I change a field from another class, like a class Goal, where I'm using now id_user, but after creating the new class Member I need to change the name of field like id_member. So old data have old name of field - id_user, but after changing I need to give the new name id_member. I have found a solution to avoid these two questions. Like in my pic: I leave everything as it is. I do not touch old data. There is no need to create automatic connections between User and Member classes. But I still have to manually add users to the Member class. And this double link, I doubt it. Of cource, I want to know the answers of all my questions. Please, if you don’t mind dispelling my doubts. -
Django POST Request: I always end up with an Error 400 and the provided data in the request doesn't get accepted
I have a django project with the following (relevant to this question) apps: Course, Category, User (Teacher) & SubCategory. Using the Django REST Framework, I am trying to override the perform_create() method, so that certain fields of the Course Model are already preoccupied when creating a new instance. I'd like the "teacher" field to be the current user, the "category" field to be the instance of the category, which is matched by the request data "category", etc. Now whenever I execute the code, I end up with a 400 Error and it says that "This field is requied" for the teacher, category, sub_category, etc. Please find the code below: Course Model class Course(models.Model): name = models.CharField(max_length=100) description = models.TextField(max_length=500) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) premium_only = models.BooleanField(default=False) duration = models.IntegerField(default=0) level = models.CharField(max_length=100) # Relationships category = models.ForeignKey( to=Category, related_name='courses', on_delete=models.CASCADE) sub_category = models.ForeignKey( to=SubCategory, related_name='courses', on_delete=models.CASCADE) teacher = models.ForeignKey( to=User, related_name='courses', on_delete=models.CASCADE) marked_as_favorite_by = models.ManyToManyField( to=User, related_name='favorite_courses', blank=True, null=True, default=None) def __str__(self): return self.name Course Views class CreateCourseView(CreateAPIView): queryset = Course.objects.all() serializer_class = CourseSerializer permission_classes = [IsAuthenticated] def perform_create(self, serializer): categories = Category.objects.all() sub_categories = SubCategory.objects.all() teacher = self.request.user category = categories.get(name=self.request.data['category']) sub_category = sub_categories.get( name=self.request.data['sub_category']) serializer.save(teacher=teacher, category=category, … -
Check Selected Fields in Django
I have a form with musicial instruments: class InstrumentForm(forms.ModelForm): instruments = forms.ModelMultipleChoiceField(queryset=Instrument.objects.all()) class Meta: model = Instrument fields = ('instruments', ) That takes all instruments from model. I need to somehow check selected instruments and save them to Profile Model: class Profile(models.Model): ... instrument = models.ManyToManyField(Instrument, related_name='instruments') def __str__(self): return f'{self.user.username} Profile' I also have a dummy html page with form, it works: <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy }} <button class="btn btn-outline-dark" type="submit">OK</button> </form> But I need to check all instruments that user has selected and save them to the user profile model, how can I do this? -
Not able to change the python version in runtime.txt
I want to deploy django app using heroku and I runned this in terminal ----> git push heroku master Following error I encountered Requested runtime (Python-3.10.4) is not available for this stack (heroku-20). remote: ! Aborting. More info: https://devcenter.heroku.com/articles/python-support remote: ! Push rejected, failed to compile Python app I'm using python version 3.10.5 which is compatible with the heroku stack. However, when I try to change the python version in runtime.txt file from python-3.10.4 to python-3.10.5. I;m not able to!!!! It says runtime.txt is only read only file! -
Best way to divide a template by sections? (multiple queried for loops?) (Django)
I have a model which lists projects - one of these fields records a projects' state as foreign key to a status model. I would like to have a view where the projects are listed, however are divided by status, for example. <h1 class="main_title">Projects</h1> <h2>Projects with a Status of 1<h2> {% for projects in projects %} <h3>> {{ projects.name_title_working }}</h3> <p>> {{ projects.fk_state }}</p> <p>> {{ projects.genre }} <p>> {{ projects.d_conceived }} {% endfor %} <h2>Projects with a Status of 2<h2> {for loop} <h2>Projects with a Status of 3<h2> {for loop} etc. How would i query at the template level like this, or would there need to be additional steps where the querying is done at a lower level? -
What's the difference returning a QuerySet or a list of it?
Suppose I have two models Book and User with a foreign key on Book. And in one of my API endpoints I return the following QuerySet: return User.objects.get(pk=user_id).posts.all() The result is correctly rendered on the browser. If I change the line to (using a list): return list(User.objects.get(pk=user_id).posts.all()) ...the output result is the same. Since QuerySet is lazy-load (being excecuted only when evaluated), my question is: What's the difference in terms of memory or performance between the two approachs? Or will return and list have the same effect (evaluating the QuerySet)? What's the best approach I should use? I read the docs but it wasn't very clear to me what happens when the QuerySet is returned or a list of it. Extra info: I'm using Ninja API based on FastAPI, but the question would be the same for context data of a django view. Thanks in advance! -
Django or Anvil Python. Which one should I learn?
I was just researching about web development in Python. Django is a well known framework for web apps in Python but recently came to know about anvil. It seemed quite easy because of drag and drop UI. Also seem new and can be a trending technology in future. I want to learn Anvil. Should it worth it? Or Django is better? Because right now most of the projects offered by companies require them to be in Django. Anvil seems reletively new and got less community. Please give some suggesstions. -
Django orm: How to annotate a model with a related relation traversing multiple table
Lets say i have this structure class lvlOne(models.Model): name = models.CharField(max_length=255) class lvlTwo(models.Model): name = models.CharField(max_length=255) parent = models.ForeignKey(lvlOne, related_name="children") class lvlThree(models.Model): name = models.CharField(max_length=255) parent = models.ForeignKey(lvlTwo) is there way to annotate instances of lvlOne with a Related Manger of lvlThree, am thinking something like this obj = lvlOne.objects.annotate(grandchildren = .... ).get() obj.children.all() # all related lvlTwo instances as expected from setting related_name obj.grandchildren.all() # all related lvlThree instances Couple things i tried Using postgres specific ArrayAGG I managed to get a similar result, but its still a list of id (or name etc) Not the actual objects. Using Prefetch() and FilteredRelation() seems to apply on immedate relation only, every time the lookup traverse to another Model, the prefetch does not happen. -
How to get a value from 1-1 table related to current user
How do i get a value points from one-to-one table that related to current user on a website. In short how to get current_user_points like a current_user_id in this code views.py current_user_points = userprofiles.points current_user_id = request.user.id models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) points = models.IntegerField(default=100) telegramID = models.CharField(max_length=9, blank=True) -
django ckeditor - call data from rich text editor
does anyone know if it is possible to call data from the richtext editor in the admin panel? My views.py looks like this: def post_detail(request, slug): posting = post.objects.get(slug=slug) try: if posting.slug == 'dividend_stocks_list': data = pd.DataFrame(stocks(request)) allData=[] for i in range(data.shape[0]): temp = data.iloc[i] allData.append(dict(temp)) context_posting = { 'title': posting.title, 'date': posting.date_added, 'intro': posting.intro, 'body': posting.body, 'data': allData } except: context_posting = { 'title': posting.title, 'date': posting.date_added, 'intro': posting.intro, 'body': posting.body, } return render(request, 'post_detail.html', context_posting) next is the html {% block content %} {% load humanize %} <h1 class="title">{{ title }}</h1> <small>Posted at {{ date }}</small> <br/> <br/> <hr/> <div>{{ intro | safe }}</div> <hr/> <div>{{ body | safe }}</div> {% endblock %} {% block js %} {% endblock %} I would like to type in the rich text editor blablabla {{ data | safe }} blablabla But till now I have not figured out how to do that. Do you have any idea? Thanks in advance. Beste regards Sandro -
Referencing external variables in Django data migrations
For models, we use apps.get_model() to make sure that the migration will use the right version of the model (as it was when the migration was defined). But how do we deal with "regular" variables (not models) imported from the codebase? Suppose I want to simply modify the value of a field with a variable that I've defined somewhere in the codebase. For example, I want to turn all normal users into admins. I stored user roles in an enum (UserRoles). One way to write the migration would be this: from django.db import migrations from user_roles import UserRoles def change_user_role(apps, schema_editor): User = apps.get_model('users', 'User') users = User.objects.filter(role=UserRoles.NORMAL_USER.value) for user in users: user.role = UserRoles.ADMIN.value User.objects.bulk_update(users, ["role"]) def revert_user_role_changes(apps, schema_editor): User = apps.get_model('users', 'User') users = User.objects.filter(role=UserRoles.ADMIN.value) for user in users: user.role = UserRoles.NORMAL_USER.value User.objects.bulk_update(users, ["role"]) class Migration(migrations.Migration): dependencies = [ ('users', '0015_auto_20220612_0824'), ] operations = [ migrations.RunPython(change_user_role, revert_user_role_changes) ] But now there are problems. If some day in the future I delete the UserRoles variable (because I change the implementation) this will break migrations. So I won't be able to re-run migrations locally to re-create a database from scratch. If I modify the variable (e.g. I change the order … -
Notification in django rest API
I want to make a notice in django that when you add a new entry to the database the admin I do everything in the Django Rest API -
Django KeyError: 'password'
I am trying to update my user profile. But at the 'if data['password'] != '':' line, it's showing a KeyError at 'password'. I am understanding the data I called at request.data doesn't contain 'password', which is not making any sense. Please help me out, someone. @api_view(['PUT']) @permission_classes([IsAuthenticated]) def updateUserProfile(request): user = request.user serializer = UserSerializerWithToken(user, many=False) data = request.data user.first_name = data['name'] user.username = data['email'] user.email = data['email'] if data['password'] != '': user.password = make_password(data['password']) user.save() return Response(serializer.data) -
LookupError: No installed app with label 'admin'/ File "/code/bookstore/urls.py", line 21, in <module>
I'm reading "Django for professionals" and practicing it. I was shown to make "docker-compose down" and up it again and I did. But after this nothing is working. It's complaining to root urls.py file where its importing admin file -
How to update Gunicorn with new datbase settings?
I'm trying to set up a website using EC2 and Django/Nginx/Gunicorn but I'm getting the following error: FATAL: database "db-name" does not exist The issue is that the database that I currently have configured is a different name "testdb", and the files in the EC2 instance are already pointing towards the different database, yet Gunicorn seems to keep trying to look for the wrong database name. I've tried restarting Gunicorn with sudo systemctl restart gunicorn and sudo systemctl daemon-reload but it still tries to look for "db-name" instead of "testdb". My wsgi.py and settings files should be correct so I don't think those are the issue. So how can I get Gunicorn to look for the right database? gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/opt/code/shop ExecStart=/opt/code/shop/venv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ core.wsgi:application Restart=always RestartSec=3 wsgi.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings') application = get_wsgi_application() core/settings.py DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": "testdb", "USER": env("DB_USER"), "PASSWORD": env("DB_PASSWORD"), "HOST": env("DB_HOST"), "PORT": env("DB_PORT"), } } -
How can I get Django Rest Framework to work with Django Tenants and React?
Here is my setup: settings.py SHARED_APPS = ( 'django_tenants', 'main', other apps... ) TENANT_APPS = ( 'rest_framework', 'company', ) MIDDLEWARE = [ 'django_tenants.middleware.main.TenantMainMiddleware', other middleware... ] DATABASE_ROUTERS = ( 'django_tenants.routers.TenantSyncRouter', ) urls.py from django.urls import include, path from rest_framework import routers # other imports from main.api.v1 import projects router = routers.DefaultRouter() router.register(r'api/v1/project', projects.ProjectViewSet) urlpatterns = [ -- other paths -- path('', include(router.urls)), ] api/v1/project.py # other imports from company.models import Project from rest_framework import serializers from rest_framework import viewsets from rest_framework import permissions class ProjectSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Project fields = ['url', 'name', 'keycode'] class ProjectViewSet(viewsets.ModelViewSet): queryset = Project.objects.all().order_by('id') serializer_class = ProjectSerializer permission_classes = [permissions.AllowAny] main.models.py from django.contrib.auth.models import User as AuthUser from django_tenants.models import TenantMixin, DomainMixin # note, definition of custom "User" model which has an AuthUser 1 to 1 relationship class Company(TenantMixin): name = models.CharField(max_length=100) subdomain = models.CharField(max_length=32) employees = models.ManyToManyField(User, related_name='companies') migration_id = models.IntegerField(null=True) class Domain(DomainMixin): pass company.models.py from django.db import models class Project(models.Model): name = models.CharField(max_length=100) keycode = models.CharField(max_length=8) And the final detail is that I am not using a Django frontend but rather one created in React. The request which is going to the backend is just a standard request however it is coming … -
Can't access variable from with a function
I have this script to create google maps with markers template inside my Django project: <script> function initMap() { const shop = { lat: 45.0203018, lng: -88.318316 }; const map = new google.maps.Map( document.getElementById("map"), { zoom: 10, center: shop, }); const vehicles = {{ vehicles|safe }}; for(i = 0; i < vehicles.length; i++){ const pos = new google.maps.LatLng(vehicles[i]['lat'],vehicles[i]['lon']); const marker = new google.maps.Marker({ position: pos, map: map, label: vehicles[i]['number'], }); const id = vehicles[i]['truck'] marker.addListener("click", () => { window.location = "{% url 'invent:truck' id %}"; }); }; }; window.initMap = initMap; </script> But it doesn't see variable id inside the addListener function. And if I put the variable inside the function it doesn't see the vehicles variable. What am I doing wrong? -
How to setup front end and back end on one server and on one port number?
The frontend and backend of the site are on the same server, on different ports: frontend in on 443, and the backend on 8443. A request is sent from the frontend to create a file from the backend (in the form of GET-requests). These requests go regularly until the file is created. But for some people, these requests are not returned. The following error appears in the console: Гипотеза заключается в том, что возможно файервол не разрешает отправлять запросы на порт 8443. Trying to just enter the web address with this port number (https://app.website.com:8443/) to the browser by these people should return the standard Django screen, but returns: Here is how the servers are configured. I additionally, just in case, made sure that any cache was deleted. This is the front end server setup: server { listen 80; server_name website.com; return 301 https://website.com; } server { listen 443 ssl default_server; listen [::]:443 ssl default_server; ssl_certificate /etc/ssl/app.website.com_ssl_certificate.cer; ssl_certificate_key /etc/ssl/app.website.com_private_key.key; root /home/website/dist; index index.html index.htm index.nginx-debian.html; server_name app.website.com; index index.html; location / { try_files $uri $uri/ /index.html; # kill cache add_header Last-Modified $date_gmt; add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0'; if_modified_since off; expires off; etag off; } } This is backend server … -
django channels - possible for "write-only" channel group?
Hopefully this is gonna make sense. I am building an app using django-channels that works a little bit like a quiz - there is a host, and multiple players. When something goes wrong in the player side of the house I want the specific player consumer to send a message to the host group - which is easy enough. Unfortunately, because all player consumers need to be attached to the host group to send messages, they also receive those and send them to their connected clients. Thus if an issue occurs with player 1's consumer, it ultimately gets broadcast to player 2, player 3, etc, when all I want to do is alert the host. I've thought about doing this with a 'no-handle' flag in such messages, but is there a cleaner method of doing what I want?