Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Correct way to store Python function definitions (names) in a database?
Context - Skip to "Crux" for tl;dr: I'm building a report automation system that includes a handful of independent "worker" daemons each with their own APScheduler instance, one central "control panel" web application in Django, and using ZMQ to manage communication between Django and the workers. The workers tasks involve querying a database, compiling reports, and saving and/or distributing exported files of those reports. Everything is running on a single server, but each worker is "assigned" to its own business unit with its own data, users, and tasks. The intent is that users will be able to use the web app to manage the scheduled jobs of their assigned worker. I'm aware of APScheduler's issue (at least in v3.x) with sharing jobstores, so instead of having Django modify the jobstores directly I'm planning on using ZMQ to send a JSON message containing instructions, which the worker will parse and execute itself. Crux: For the web user (assumed to have zero programming proficiency) to be able to add new scheduled jobs to the worker, the web app needs to provide a list of "possible tasks" that the worker can execute. Since the tasks are (primarily) reports to be produced, using the … -
How to dynamically switch databases for multi-tenancy in Django without modifying core settings?
I’m working on implementing multi-tenancy for a Django application, where each tenant will have a separate database. I create the databases dynamically when a new tenant is created and need to switch to the tenant's database for each request. Since the databases are created on the fly, I cannot register them in the settings.py file. To achieve this, I plan to create middleware that intercepts the request, checks for the authenticated user, retrieves the appropriate database for that user, and dynamically switches to it for the request. However, I'm unsure about how to correctly implement this in Django, given its default database handling behavior. I need guidance on: Where to modify the code: What files or areas of Django need to be adjusted to make this work? Database switching: How do I properly switch to a dynamically created database per user without affecting other requests? Database routers: How do I use database routers to manage connections dynamically in my custom setup? Considerations for querysets and operations: What should I keep in mind when querying data or performing operations on the dynamically selected database? I’m looking for a solution that doesn’t require me to modify the core application heavily and would … -
Order by subset of related field?
I have a model Release. Each release has a type, and depending on that type different types of Credit are considered primary credits. I want to be able to order releases by the Entity names of their primary credits. class Release(models.Model): TYPES = { "GA": "Game", "MO": "Movie", "TV": "TV Show", "MU": "Music", "BO": "Book", "BU": "Bundle" } TYPES_PRIMARY_ROLE = { "GA": "Developer", "MO": "Director", "TV": "Showrunner", "MU": "Primary Artist", "BO": "Author", "BU": "none" } type = models.CharField(choices=TYPES) # How to order_by the entity__names returned here? def get_credits_primary(self): return self.credits.filter(role__name=self.TYPES_PRIMARY_ROLE[self.type]).order_by("entity__name") class Credit(models.Model): role = models.ForeignKey(CreditRole, on_delete=models.CASCADE, related_name="credits") entity = models.ForeignKey(Entity, on_delete=models.CASCADE, related_name="credits") release = models.ForeignKey(Release, on_delete=models.CASCADE, related_name="credits") I suppose I could create a cached string value of the primary credit names, but that doesn't seem like a good way to do it. -
django.db.utils.OperationalError: no such column: dashboard_player.player_run
class Player(models.Model): role_choices = [ ('Batsman', 'Batsman'), ('Bowler', 'Bowler'), ('AllRounder', 'AllRounder'), ('WicketKeeper', 'WicketKeeper'), ] player_name = models.CharField(max_length=30, blank=False) player_team = models.ForeignKey(Team, on_delete=models.CASCADE, blank=False) match_number = models.ForeignKey(Match, on_delete=models.CASCADE, blank=False) player_role = models.CharField(choices=role_choices, max_length=15, blank=False) player_available = models.BooleanField(default=True) player_number = models.IntegerField(null=True, editable=False) player_run = models.IntegerField(blank=True, null=True, default=0) player_wickets = models.IntegerField(blank=True, null=True, default=0) player_catch = models.IntegerField(blank=True, null=False, default=0) def __str__(self): return f"{self.player_name} ({self.player_role})" after adding player_run, player_wickets, player_catch I ran the migration commands which asked for a default value to which i mistakenly added datetime to it. But now whenever i try to save any player it says raise e.__class__( TypeError: Field 'player_catch' expected a number but got datetime.datetime(2025, 2, 6, 10, 53, 15, 330920, tzinfo=datetime.timezone.utc). and the api response is 'table dashboard_player has no column named player_run' Can anyone tell what can be the problem in this code? -
Configuration of Django+WSGI+Apache
I have a Debian 11 system with Apache2 2.4.6.2, mod_wsgi 4.7.1 and Python 3.9. I want to run two different Django projects under the same Apache2 server, and in the same virtual host as outlined e.g. here: http://www.tobiashinz.com/2019/04/10/apache-django-virtualenv.html The following additions in the apache2.conf have worked fine to get one Django project online: WSGIApplicationGroup %{GLOBAL} WSGIDaemonProcess myapp python-home=/var/www/myproj/venv3/ python-path=/var/www/myproj/myproj WSGIProcessGroup myapp WSGIScriptAlias / /var/www/myproj/myproj/wsgi.py To configure the second Django, I first tried to move the configuration of the first project to a virtual host section. However, if I move the configurations to a virtual host in available-sites (e.g. in 000-default.conf), I do not get any error message (e.g. in the apache error log), but instead of my Django project, I see the default apache2 landing page ("It works!"), even if I comment out DocumentRoot. Am I missing something? -
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 a VueJS search page API call. Basically, I want to know how to implement my VueJS search page API call with the search_query_set API endpoint in my views, like I did with the the VueJS API calls for the Login/Register API endpoints Here are some files that may be of some use to you. serializers.py class CompanySerializer(HaystackSerializer): class Meta: index_class = [ArboristCompanyIndex] fields = [ 'text', 'company_name', 'company_city', 'company_state' ] search_indexes.py class ArboristCompanyIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.EdgeNgramField(document=True, use_template=True) company_name = indexes.CharField(model_attr='company_name') company_city = indexes.CharField(model_attr='company_city') company_state = indexes.CharField(model_attr='company_state') # Instead of directly indexing company_price, use the price_display method company_price_display = indexes.CharField(model_attr='price_display', null=True) # Using the custom price_display method experience = indexes.CharField(model_attr='experience') def get_model(self): return ArboristCompany def index_queryset(self, using=None): return self.get_model().objects.filter(content='foo').order_by('company_name', 'company_city', 'company_state', 'experience') views @authentication_classes([JWTAuthentication]) class LoginView(APIView): def post(self, request, *args, **kwargs): serializer = LoginSerializers(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] login(None, user) token = Token.objects.create(user=user) return Response({"status": status.HTTP_200_OK, "Token": token.key}) if user is not None: # Generate token refresh = … -
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 February, but instead, it's showing "new" for both January and February, and only switching to "active" in March. The same issue is happening with the "deleted" status. It should show as "deleted" in January and change to "not visible anymore" in February. However, it's showing as "deleted" in January, February, and March, and then disappears entirely in April. What could be causing this issue? I assume it is the wrong timestamps that were set up, but I am not sure how to redefine them. class ReportView(View): template_name = "reports/report.html" def get(self, request): context = { 'menu': get_service_menu_data(), } return render(request, self.template_name, context) def post(self, request): logger.info(f"Request: {request.method} {request.path}?{str(request.body)[str(request.body).index('&') + 1:-1]}") form = csv_form(request.POST) if form.is_valid(): company = form.cleaned_data.get('company') month = form.cleaned_data.get('month') year = form.cleaned_data.get('year') date_from = datetime.date(int(year), int(month), 1) date_to = datetime.date(int(year), int(month), calendar.monthrange(int(year), int(month))[1]) + datetime.timedelta(days=1) prev_month = date_from - relativedelta(months=1) next_month = date_to + relativedelta(months=1) current_numbers = PhoneNumberHolder.objects.filter( billing_group__billing_group=company, purchased__lte=date_to ).exclude( terminated__lt=date_from ) prev_numbers = PhoneNumberHolder.objects.filter( billing_group__billing_group=company, purchased__lte=prev_month … -
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" and is unable to process any requests due to database connections dropping. I've attached a stack trace bellow but they really make no sense whatsoerver to me. I'm using postgres without any short timeouts (database side) and the way I setup the connectiong enables healthchecks at every request, which I'd assume would get rid of any "stale connection" style issues: DATABASES = { "default": dj_database_url.config( default="postgres://postgres:pass@localhost:5432/db_name", conn_max_age=300, conn_health_checks=True, ) } I'm curious if anyone has any idea as to how I'd go about debugging this? It's really making the django ORM unusable due to apps going down spontanously. Stacktrace bellow is an example of the kind of error I get here: Traceback (most recent call last): File "/home/ubuntu/py_venv/lib/python3.12/site-packages/uvicorn/protocols/http/h11_impl.py", line 403, in run_asgi result = await app( # type: ignore[func-returns-value] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/ubuntu/py_venv/lib/python3.12/site-packages/uvicorn/middleware/proxy_headers.py", line 60, in __call__ return await self.app(scope, receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/ubuntu/py_venv/lib/python3.12/site-packages/fastapi/applications.py", line 1054, in __call__ await super().__call__(scope, receive, send) File "/home/ubuntu/py_venv/lib/python3.12/site-packages/starlette/applications.py", line 113, in __call__ await self.middleware_stack(scope, … -
Do we need to keep a flow of migration files from development to production?
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 migrate. While doing these thing I deal with lot of migrarion issues. when I run python manage.py makemigrations appname it detect the new changes in models.py I hae also verified in migration files it is added but when i run python manage.py migrate it say tat no migrations to apply and in the end I need to delete the database and create databse again then do makemigrations and migrate. But I can't do this at production level. Below is one of the error im getting. This is the response while running migrate command. root@98d07ed814b3:/app# python manage.py migrate Operations to perform: Apply all migrations: admin, auth, communityEmpowerment, contenttypes, django_celery_beat, sessions, token_blacklist Running migrations: No migrations to apply. root@98d07ed814b3:/app# I have tried faking migrations. delete migrations files and migrate it again but none of them worked. I want someone who can explain everything about django migrations and these common issues. -
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 of the content I am using @tailwindcss/typography. I have added prose class in the content container. I have tried to override the css classes. like, .prose p:empty{ margin: 0; } But it didn't work. So I created a django custom filter to remove the content. from django import template from django.utils.safestring import mark_safe import re register = template.Library() @register.filter def remove_empty_paragraphs(value): # Remove empty <p> tags cleaned_value = re.sub(r'<p[^>]*>\s*</p>', '&nbsp;', value) return mark_safe(cleaned_value) I have tried with both '' blank string and &nbsp; because in the developer console, there is showing &nbsp; inside the p tag. Still didn't work. -
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 up Vite in my Django project: Installed Tailwind CSS v4 and Vite in a webapp/ directory. Running npm run dev serves styles, and npm run build outputs to dist/. Configured Vite (vite.config.js): import { defineConfig } from 'vite'; import { resolve } from 'path'; import tailwindcss from '@tailwindcss/vite'; export default defineConfig({ plugins: [ tailwindcss(), ], base: '/static/', // Important for Django to locate assets build: { manifest: true, emptyOutDir: true, outDir: resolve(__dirname, 'dist'), // Ensure the output folder is 'dist' rollupOptions: { input: { tailwind: resolve(__dirname, 'src/style.css'), }, }, }, server: { watch: { usePolling: true, // Ensures Django templates are watched ignored: ['!../templates/**/*'], // Make sure templates are included }, }, }); Configured Django Static Files (settings.py): STATIC_URL = 'static/' STATIC_ROOT = BASE_DIR / 'staticfiles' STATICFILES_DIRS = [ BASE_DIR / "webapp/dist" # Matches vite config! ] DJANGO_VITE = { "default": { "dev_mode": DEBUG, } } Updated My Django Template (templates/home.html): <!-- templates/home.html --> {% load django_vite %} <!doctype html> <html … -
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. So then I tried installing gettext. sudo apt update && sudo apt install gettext -y After installation, I still get the same error when running python manage.py compilemessages. Checked if msgfmt is installed by msgfmt --version but it says: command not found OS is Ubuntu and Django version is 4.2.5. How can I resolve this issue and make Django recognize msgfmt? Any help would be appreciated! -
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? Why do we call super() here? Why do we call the same method (get_queryset) inside itself? I've tried to understand it, but explanations so far haven't made it clear to me. I would appreciate a simple and satisfying answer. -
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', 'زمانی که نیستم' never = 'never', 'هرگز' class Previous_Replies_Choices(models.TextChoices): always = 'always', 'همیشه' unless_previously_send = 'unless_previously_send', 'مگر اینکه قبلا ارسال شده باشد' never = 'never', 'هرگز' class Mailing_list_mode_Choices(models.TextChoices): send_email_for_new_post = 'send_email_for_new_post', 'ارسال ایمیل برای هر پست جدید' send_email_for_new_post_except_mine = 'send_email_for_new_post_except_mine', 'ارسال ایمیل برای هر پست جدید به جز پست های خودم' class Topic_As_New_Choices(models.TextChoices): i_have_not_viewed_them_yet = 'I_have_not_viewed_them_yet', 'آنهایی که هنوز ندیده ام' created_in_the_last_day = 'Created_in_the_last_day', 'در روز گذشته ایجاد شده باشد' created_in_the_last_2_days = 'Created_in_the_last_2_days', 'در دو روز گذشته ایجاد شده باشد' created_in_the_last_week = 'Created_in_the_last_week', 'در هفته گذشته ایجاد شده باشد' created_in_the_last_2_weeks = 'Created_in_the_last_2_weeks', 'در دو هفته گذشنه ایجاد شده باشد' created_since_i_was_here_last = 'Created_since_i_was_here_last', 'پس از آخرین باری که اینجا بودم ایجاد شده باشد' id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField(max_length=256 , unique=True) # username = None USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['USERNAME_FIELD'] session_token = models.CharField(max_length=10, default=0) date_joined = models.DateTimeField(verbose_name='تاریخ عضویت',auto_now_add=True, editable=True) trust_level = models.CharField(choices=Trust_Level_choices, verbose_name='سطح اعتماد', max_length=20) profile_picture = models.ImageField(verbose_name='تصویر پروفایل') send_email_for_p_m = models.CharField(choices=Personal_Message_Choices, verbose_name='ارسال ایمیل برای پیام های شخصی', max_length=20) send_email_when_q_r_m_na_in_w = … -
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 be set. from django.contrib.auth import get_user_model from django.contrib.auth.tokens import default_token_generator from django.utils.http import urlsafe_base64_decode from django.shortcuts import render, redirect from django.contrib import messages from .models import UserProfile from .forms import RegistrationForm User = get_user_model() def complete_registration_step1(request, uidb64, token): try: uid = urlsafe_base64_decode(uidb64).decode() user = User.objects.get(pk=uid) # Check if the token is valid and hasn't been used if user.token_used or not default_token_generator.check_token(user, token): messages.error(request, "The confirmation link is invalid or expired.") return redirect('home') except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None: if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): user_profile, created = UserProfile.objects.get_or_create(user=user) # Error occurs here form_instance = form.save(commit=False) user_profile.first_name = form_instance.first_name user_profile.birth_date = form_instance.birth_date user_profile.gender = form_instance.gender user_profile.save() messages.success(request, "First step of registration completed.") # return redirect('complete_registration_step2', uidb64=uidb64, token=token) else: form = RegistrationForm() return render(request, 'registration/complete_registration.html', {'form': form}) else: messages.error(request, "User does not exist.") return redirect('home') from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models class CustomUserManager(BaseUserManager): def create_user(self, email, username=None, password=None, **extra_fields): … -
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 the user with admin_create_user of boto3.client. So far so good, the user is created. When it comes to handling the login, we are encountering problems with the CUSTOM_AUTH for admin_initiate_auth: try: initiate_resp = cognito_client.admin_initiate_auth( UserPoolId=settings.AWS_COGNITO_USER_POOL_ID, ClientId=settings.AWS_COGNITO_CLIENT_ID, AuthFlow="CUSTOM_AUTH", AuthParameters={ "USERNAME": email, "SECRET_HASH": get_secret_hash(email) } ) print(initiate_resp) except ClientError as e: return {"error": f"admin_initiate_auth failed: {str(e)}"}, 400 We have added, as per documentation the lambda triggers to for define_auth_challenge: def lambda_handler(event, context): """ Cognito calls this to decide which challenge to present next (or issue tokens). We'll always present a CUSTOM_CHALLENGE if there's no successful challenge yet. """ # event["request"]["session"] contains prior challenge attempts. # If empty, it's the user's first attempt this auth session. session_list = event["request"].get("session", []) if len(session_list) == 0: # First time => present the custom challenge event["response"]["challengeName"] = "CUSTOM_CHALLENGE" event["response"]["issueTokens"] = False event["response"]["failAuthentication"] = False print("DefineAuthChallenge -> Presenting CUSTOM_CHALLENGE (first attempt)") else: # Check the last challenge last_challenge = session_list[-1] if last_challenge.get("challengeResult") is True: # If they … -
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 and then how to integrate it with django. I tried to pull the elasticsearch image and run the container on -p 4200:4300 but it keeps getting error. still manages to run but again getting Active licence error. added in settings.py ELASTICSEARCH_DSL = { 'default': { 'hosts': ['http://localhost:9300'], 'http_auth': ('elastic', 'password'), }, } Getting Connection Error. what should be username and password when first setup? what should be the url? does we really need a certificate? where to download certificate? does we really need to configure each time while project setup? PS. I am really beginner in elasticsearch really need to learn it. -
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: context: . dockerfile: ./compose/local/django/Dockerfile image: my_project_local_django container_name: my_project_local_django depends_on: - postgres - redis volumes: - .:/app:z - ./media:/app/media # To make sure that /media hooks up to Celery. env_file: - ./.envs/.local/.django - ./.envs/.local/.postgres ports: - "8000:8000" command: /start postgres: ... redis: image: redis:6 container_name: my_project_local_redis volumes: - my_project_local_local_redis_data:/data celeryworker: <<: *django image: my_project_local_celeryworker container_name: my_project_local_celeryworker volumes: - ./media:/app/media # To ensure Celery has access to local /media directory. depends_on: - redis - postgres ports: [] command: /start-celeryworker celerybeat: <<: *django image: my_project_local_celerybeat container_name: my_project_local_celerybeat volumes: - ./media:/app/media # To ensure Celery has access to local /media directory. depends_on: - redis - postgres - django restart: always ports: [] command: /start-celerybeat flower: <<: *django image: my_project_local_flower container_name: my_project_local_flower ports: - "5555:5555" command: /start-flower And here's the task. So far I'm just testing a simple scenario of generating a blank file. ... @celery_app.task() def generate_file(object_id): lock_key = f"generate_file_task_lock:{object_id}" # Try to acquire the lock if redis_client.set(lock_key, "locked", ex=60, nx=True): # `nx=True` ensures … -
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 token is valid, the user should be authenticated. I am using Django templates but haven't found clear documentation or articles on how to implement this. How can I achieve this using Django-Allauth? Any guidance or references would be greatly appreciated! Thank you. i tried the following implementation using allauth : # setting.py ACCOUNT_EMAIL_REQUIRED = True LOGIN_REDIRECT_URL = "/admin" ACCOUNT_AUTHENTICATION_METHOD = "email" ACCOUNT_CONFIRM_EMAIL_ON_GET = True ACCOUNT_EMAIL_VERIFICATION = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_USER_MODEL_USERNAME_FIELD = None # Remove `username` field ACCOUNT_PASSWORD_REQUIRED = False # Allows empty passwords ACCOUNT_SESSION_REMEMBER = True ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True # Auto-login after confirmation ACCOUNT_EMAIL_VERIFICATION = "mandatory" # Ensures users verify their email ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = False AUTH_USER_MODEL = "users.CustomUser" ACCOUNT_ADAPTER = "users.adapters.CustomAccountAdapter" ACCOUNT_FORMS = { "signup": "users.forms.CustomSignupForm", "login": "users.forms.CustomLoginForm", } EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend" # forms.py file from allauth.account.forms import SignupForm from django import forms class CustomSignupForm(SignupForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if "password1" in self.fields: del self.fields["password1"] # Remove password fields if "password2" in self.fields: del self.fields["password2"] def save(self, … -
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 way for users to stop an ongoing StreamingHttpResponse. We are looking for a solution to terminate the stream early if needed—without using WebSockets and without relying on Redis or other services that require VPC connectors, as they are costly for us at the moment. Is there a way to achieve this within our existing Google Cloud Run setup? -
"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 = tracker.SummaryTracker() [...] tr.print_diff() return Response(...) I get this error: File "src/api/views/case_manager/dashboard/dashboard_viewset.py", line 33, in list tr = tracker.SummaryTracker() File "lib/python3.13/site-packages/pympler/tracker.py", line 45, in __init__ self.s0 = summary.summarize(muppy.get_objects()) ~~~~~~~~~~~~~~~~~^^ File "lib/python3.13/site-packages/pympler/muppy.py", line 42, in get_objects tmp = [o for o in tmp if not ignore_object(o)] ~~~~~~~~~~~~~^^^ File "lib/python3.13/site-packages/pympler/muppy.py", line 17, in ignore_object return isframe(obj) File "lib/python3.13/inspect.py", line 507, in isframe return isinstance(object, types.FrameType) File "lib/python3.13/site-packages/django/utils/functional.py", line 280, in __getattribute__ value = super().__getattribute__(name) File "lib/python3.13/site-packages/django/utils/functional.py", line 251, in inner self._setup() ~~~~~~~~~~~^^ File "lib/python3.13/site-packages/django/contrib/admin/sites.py", line 605, in _setup AdminSiteClass = import_string(apps.get_app_config("admin").default_site) ~~~~~~~~~~~~~~~~~~~^^^^^^^^^ File "lib/python3.13/site-packages/django/apps/registry.py", line 165, in get_app_config raise LookupError(message) LookupError: No installed app with label 'admin'. This seems to happen as a DefaultAdminSite is always created, lazily, in a global variable, which muppy accesses to get the size. Any idea how to work around this? -
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 = os.environ.get("EMAIL_HOST") EMAIL_HOST_PASSWORD = os.environ.get("EMAIL_HOST_PASSWORD") DEFAULT_FROM_EMAIL = os.environ.get("EMAIL_HOST") EMAIL_PORT = 465 EMAIL_USE_SSL = True EMAIL_USE_TLS = False I've set my environment variables as follows: EMAIL_HOST = ABC@dagger.com # GoDaddy email EMAIL_HOST_PASSWORD = Abc@1223 # GoDaddy email password However, when trying to send an email, I get the following error: File "C:\Users\jinal.desai\AppData\Local\Programs\Python\Python310\lib\ssl.py", line 1071, in _create self.do_handshake() File "C:\Users\jinal.desai\AppData\Local\Programs\Python\Python310\lib\ssl.py", line 1342, in do_handshake self._sslobj.do_handshake() ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1007) What I've Tried: Verified that my GoDaddy email credentials are correct. Tried setting EMAIL_USE_TLS = True and EMAIL_USE_SSL = False. Used EMAIL_PORT = 587 instead of 465. Manually verified that smtpout.secureserver.net works using an external email client. Attempted to disable SSL certificate verification using: import ssl ssl._create_default_https_context = ssl._create_unverified_context Question: How can I fix this SSL certificate verification error with GoDaddy's SMTP? Do I need to install or trust a specific SSL certificate for GoDaddy's mail server? Is there any known workaround to resolve this … -
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 site admin</title> <link rel="stylesheet" href="/staticfiles/admin/css/base.css"> <link rel="stylesheet" href="/staticfiles/admin/css/dark_mode.css"> <script src="/staticfiles/admin/js/theme.js"></script> <link rel="stylesheet" href="/staticfiles/admin/css/nav_sidebar.css"> <script src="/staticfiles/admin/js/nav_sidebar.js" defer></script> <link rel="stylesheet" href="/staticfiles/admin/css/login.css"> and I checked - all files exist inbb staticfiles directory. But when i click file in chrome - such page appears Page not found (404) Request Method: GET Request URL: http://amodule.su/staticfiles/admin/css/nav_sidebar.css Using the URLconf defined in amodule.urls, Django tried these URL patterns, in this order: [name='home'] news/ admin/ The current path, staticfiles/admin/css/nav_sidebar.css, didn’t match any of these. my settings.py contains such definitions of static: STATIC_URL = 'staticfiles/' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') where am I wrong? -
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 Github)): class Project(models.Model): [...] class ProjectObjectiveCondition(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) With a custom inline admin template (on Github), the inlines look like this: What you are seeing there is: Objective: Agreeableness Level: Started Condition: Speaks pleasantly Condition: Doesn't shout Level: First results Condition: Accepts thanks with gracce Level: Mature results Condition: Apologises with sincerity Objective: Colourfulness Level: Started Condition: Has blue ... and so on The Conditions are grouped by Objective and Level through repeated use of {% regroup %} in the template. Date/commitment columns You can also see columns for the dates (instances of the WorkCycle class) and their True/False values, that show whether a commitment was made for this Project, and to reach which Level, in which WorkCycle (i.e. in which year). I want to replace those with editable tick-boxes. I actually have another inline, LevelCommitmentInline, which allows me to edit those True/False values for that model - but I don't want them in a long list somewhere else, I want … -
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 no longer loads properly and is just stuck saying loading so the contents are no longer visible on the specified page and the comment section isn't visible either. What I Tried & Expected Outcome: Fetching Blog Posts: Used axios.get('http://127.0.0.1:8000/api/blogs/') inside useEffect(). I had Expected posts to load, but they do not appear. Deleting Blog Posts: Used axios.delete(\http://127.0.0.1:8000/api/blogs/delete/$%7BblogId%7D/%5C%5C%5C%60, { headers: { Authorization: `Token ${user.token}` } })`. Expected blog deletion to work, but encountered errors. Commenting System: Implemented a comment section using axios.post() to submit new comments but nothing is being displayed at all its just stuck saying loading. Expected comments to display but they do not appear. Here's The backend snippet of the code im trying to run @api_view(['GET', 'POST']) @authentication_classes([TokenAuthentication]) @permission_classes([IsAuthenticated]) def blog_comments(request, blog_id): """ GET /blogs/<blog_id>/comments/ Returns: All comments for specified blog POST /blogs/<blog_id>/comments/ Required data: content, parent (optional for replies) Returns: Created comment data Requires: Authentication Token """ blog = get_object_or_404(Blog, id=blog_id) if request.method == 'GET': comments = …