Django and Python "Questions and answers"

06.02.2025
I need some guidance with finishing my customized api endpoints for my search query in my Django views

I’m trying to finish customizing the search_query_setfor ArboristCompany in my Django views. I’m following the Django-Haystack docs. I’m also using DRF-Haystack. In the docs, it shows you how to set up the search_querty_setviews with template files. However, I already have …

06.02.2025
Django Status Transition Issue: Incorrect Status Update for 'New', 'Active', and 'Deleted'

I have a question. I recently noticed that the statuses aren't updating correctly from "new" to "active" and from "deleted" to "not visible anymore." For example, the program should show the "new" status in January and switch to "active" in …

06.02.2025
Django ORM sporadically dies when ran in fastAPI endpoints using gunicorn

I'm using the django ORM outside of a django app, in async fastapi endpoints that I'm running with gunicorn. All works fine except that once in a blue moon I get these odd errors where a worker seemingly "goes defunct" …

06.02.2025
Do we need to keep a flow of migration files from development to production? [duplicate]

I was not pushing migration files to git and devops team making migration on their side when I do some changes in models. In development phase i played a lot with models added and removed some models made migrations and …

06.02.2025
How to remove empty paragraph tags generated in ckeditor content

I am using ckeditor5 in my django web app. The issue is, if the content contains any blank line, it's become an p tag and taking a default margin. As I am using tailwind css to get the default styles …

06.02.2025
How to Make Tailwind v4 Detect CSS Classes in Django Templates Using Vite?

I'm integrating Tailwind CSS v4 with Django using Vite, but I'm facing an issue where Tailwind only detects classes from the Vite app and does not recognize new classes added in Django templates. What I’ve Done So Far: Set …

06.02.2025
Django "compilemessages" error: Can't find msgfmt (GNU gettext) on Ubuntu VPS

I am trying to compile translation messages in my Django project by running the following command: python manage.py compilemessages However, I get this error: CommandError: Can't find msgfmt. Make sure you have GNU gettext tools 0.15 or newer installed. …

05.02.2025
Why do we call super().get_queryset() in Django's get_queryset method?

I have a method in my Django project: def get_queryset(self): queryset = super(OrderListView, self).get_queryset() return queryset.filter(initiator=self.request.user) I don’t understand why we use queryset = super(OrderListView, self).get_queryset() inside get_queryset. What is the purpose of this line? What exactly does it do? …

05.02.2025
Having two lookup field in viewset in DRF

I have three models as fallow customuser class CustomUser(AbstractUser): class Trust_Level_choices(models.TextChoices): basic_user = 'basic_user', 'عضو ابتدایی' member = 'member', 'عضو' moderator = 'moderator', 'ناظر' admin = 'admin', 'راهبر' class Personal_Message_Choices(models.TextChoices): always = 'always', 'همیشه' when_away = 'when_away', 'زمانی که نیستم' …

05.02.2025
Django Custom User Model - "The given username must be set" Error in Registration View

I'm working on a Django registration flow where users receive a tokenized link to complete their registration. During the process, I associate a UserProfile instance with the user using get_or_create(). However, I encounter an error stating that the username must …

05.02.2025
Cognito - AdminInitiateAuth fails with NotAuthorizedException

We are currently implementing an app and its corresponding backend with three options to login / signup, Google, Apple and via Email/Password. When a user chooses Apple or Google and the user is not existing in Cognito, we are creating …

05.02.2025
How to intergrate and work with django and elasticsearch?

So, I recently encountered with elasticsearch and find it really helpful to integrate with django for faster api response. But, did not able to find a good installation documentation of elasticsearch with django with step by step installation of elasticsearch …

05.02.2025
Celery on docker to generate files in the application directory

I have a Django application with Celery as delayed task mechanism. There are some file operations which I'd like to transfer to Celery to relieve Django of time consuming processes. Here's how my docker-compose looks: ... services: django: &django build: …

05.02.2025
How to Modify Django-Allauth for Passwordless Authentication Using JWT and Email Links?

I am trying to modify Django-Allauth to allow login and registration without a password. When a user attempts to register or log in, an email should be sent to their inbox containing a link with a JWT token. If the …

05.02.2025
How to stop StreamingHttpResponse in Django on Google Cloud Run?

We have integrated the GPT API in our Django application running on Google Cloud Run. When a user makes a request, we send them a response using StreamingHttpResponse from django.http, enabling real-time streaming. However, we currently do not have a …

05.02.2025
"LookupError: No installed app with label 'admin'." when using muppy in django

I have a django + drf application that has no admin site, which works very well for us. However, when using pympler and muppy like this: class DashboardViewSet( SpecialEndpoint, ): def list(self, request, *args, **kwargs): from pympler import tracker tr …

05.02.2025
Django Email Configuration: SSL Certificate Verification Failed with GoDaddy SMTP Server

I'm trying to configure Django to send emails using GoDaddy's SMTP server (smtpout.secureserver.net). My email account was created on GoDaddy, and I have the following settings in my settings.py file: import os MAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtpout.secureserver.net' EMAIL_HOST_USER = …

05.02.2025
Django admin: strange view

Couldnt understand what wrong with my admin part. It looks like that: I understood that this effect may depend on 'static' resources.. HTML preview shows: <head> <title>Log in | Django …

04.02.2025
Handling multiple related objects in the admin without using inlines

I am customising Django's admin for a particular view on some data. Where I have got so far I have a Project model, and a ProjectObjectConditions model that has a ForeignKey to it (the actual models (on …

04.02.2025
React Blog Page Not Loading & Comments Section Not Working

I am working on a React blog page where users can view blog posts and leave comments (similar to YouTube's comment section). However, after clicking on the blog page and clicking on a blog I wish to view the content …

04.02.2025
Import Error: module does not define a "CustomJWTAuthentication" attribute/class

I'm building a REST Auth API with Django/DRF. All of a sudden when I start working today, I'm getting this error message in my cli: ImportError: Could not import 'users.authentication.CustomJWTAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'. ImportError: Module "users.authentication" does not define …

04.02.2025
Unit testing Amazon SES in Django: emails not being sent

Creating unit tests for Amazon Simple Email Service (SES) for a Django application using package django-ses test_mail.py from django.core import mail ... def test_send_direct_email(send_ct): from_email = settings.SERVER_EMAIL to_email = [nt[2] for nt in settings.NOTIFICATIONS_TESTERS] starttime …

04.02.2025
Gmail Oauth2 - restrict the scope to only emails from a certain domain

I have a Django site that uses Google Oauth2 to allow users to grant access to read and reply to their emails. GOOGLE_OAUTH2_CREDENTIALS = { 'client_id': '********************', 'client_secret': '*******', 'scope': [ 'https://www.googleapis.com/auth/gmail.readonly', 'https://www.googleapis.com/auth/gmail.send' ], 'redirect_uri': 'https://www.********.com/*****/', } …

04.02.2025
How to filter data obtained through annotation?

There are 'images' that are attached to 'objects' through a ForeignKey, they can be several at each 'object'. There are 'subjects' that are also attached to 'objects' through ForeignKey. How to attach 'subject' one image from the 'object', noticed "select=1"? …

04.02.2025
CSV Timed RotatingFileHandler not rotating files

We need to fulfil a request for our Python (v3.11.7) Django (v3.2.23) app to log specific security related events on a csv file that will be rotated on an hourly basis and have a filename like audit_logs20250130_0800-0900.csv. Our Django back-end …

04.02.2025
How to recreate the database for every Django test case?

I want to write test cases for django that use the database and change its entries. I want to create a new database for every test. How do I force django to delete the entire database after every testcase (either …

04.02.2025
Django not loading image files with static

I have been working with Django and it isn't loading any image files but it is loading my CSS files in the same directory area. HTML page <!DOCTYPE html> <html lang="en"> {% load static %} <head> <meta charset="UTF-8"> …

04.02.2025
Django and AWS Lambda runtime configuration change

I have a business application written in Django where each tenant should have a completely separate environment, including: Separate database schema Separate Redis instance Separate S3 bucket, etc. However, I want to deploy a single instance of the application on …

04.02.2025
Django REST Framework: Custom Action (POST) without Serializer

I am using Django REST Framework (DRF) and have a ModelViewSet with a custom action (@action) for canceling an order. The cancel action does not require a serializer since it only modifies the database and returns a response. However, when …

04.02.2025
How to send images as a binary data with the request

Here's what I have models.py class Post(models.Model): id = models.AutoField(primary_key=True) text = models.TextField(max_length=165) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.author} posts "{self.text}"' class Images(models.Model): id = models.AutoField(primary_key=True) image = models.ImageField(upload_to='images/') post_id = models.ForeignKey(Post, on_delete=models.CASCADE) def __str__(self): …

04.02.2025
Saving a django modelform to model db

The following code is not saving to the db, the code works well in shell. everything is fine but not saving to db.could someone figure it out? def loginapp(request): if request.method == "POST": form=LoginInterfaceForm(request.POST) if form.is_valid(): form.clean() login = form.save(commit=False) …

04.02.2025
How to entry to a function in python breakpoint in terminal

I try to entry to a function that I called on my code but in terminal, pdb just go through it like this I share with you : -> def get_context_data(self, *args, **context): (Pdb) n --Return-- > d:\rebound\rebound\modules\blog\views.py(135)PostDetail()-><cell at 0x00...1DA4A0: …

03.02.2025
Expand a QuerySet with all related objects

Class Hobby(models.Model): name = models.TextField() class Person(models.Model): name = models.TextField() created_at = models.DateTimeField(auto_now_add=True) hobbies = models.ManyToManyField(Hobby, related_name='persons') class TShirt(models.Model): name = models.TextField() person = models.ForeignKey( Person, related_name='tshirts', on_delete=models.CASCADE, ) class Shirt(models.Model): name = models.TextField() person = models.ForeignKey( Person, …

03.02.2025
Can i user djangos admin for users also , i am buildng an algo trading bot in django [closed]

Currently, I am building an algorithmic trading bot with Django, and I don't expect many users—mainly just me and a few of my friends. Given this, do I need to implement custom templates for user interfaces, or can I simply …

03.02.2025
Queryset pagination in websocket django rest framework [closed]

I have a websocket in my django drf project and a function that should read all of Notification objects from database and return them via a serializer like bellow : @database_sync_to_async def get_all_notifications(self): paginator = CustomPageNumberPagination() notifications = …

03.02.2025
How to create graphql type for a django model which has many-to-many field

I have django model named profiles. It has some basic fields and many-to-many field followers. This field contains a list of followers and following peoples class Profile(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE) birth_date = models.DateField( null=True, blank=True) profile_picture = models.ImageField( …

03.02.2025
Improve the query structure or how can i use prefetch related

I have a situation and I'm not able to think of how to use prefetch_related or improve the structure of my query, here is the scenario - rows = DocumentRows.objects.filter(item=item_id).values_list("document", flat=True) qs = Document.objects.filter(id__in = rows) return qs Document …

03.02.2025
WebSocket Returns 200 Instead of 101 with Apache2: How to Properly Configure Proxy for WebSocket Handling?

I am trying to configure Apache2 to proxy WebSocket traffic for my application, but I’m facing an issue where the WebSocket connection returns a 200 status instead of the expected 101 status code. I have the following configuration in my …

03.02.2025
Why am I getting a 404 error with /None appended to the URL in my Django application? [closed]

It appears that after every successful request to a valid URL (e.g., /tasks/manager-dashboard/, /users/admin/dashboard/, etc.), an additional request is made to the same URL but with None appended to the end (e.g., /tasks/manager-dashboard/None). This results in a 404 Not Found …

03.02.2025
Dockerized Django admin failing

I've no idea where to go with this as its deep into the admin templates. I haven't touched any of it, obviously. This is a project I am moving over to a django container. It worked in the VM just …