Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django testing: find link in email message
I'm trying to test email activation and password reset. How do I filter the email body down to a usable link? def test_activation(self): self.register_user() mail.outbox[0].body.find_the_link() # Find the link here response = self.client.get(link) self.assertEqual(response.status_code, 200) -
Sending data to a form using data from previous GET request
I have a dictionary app where users can view the words (Lemma) filtered by their first letter. I would like for users to be able to then filter those results according to combinations of part of speech (each Lemma has exactly one part of speech) or tags (each Lemma can have 0 to many tags); e.g., select only Lemma that are nouns or verbs or are tagged as agricultural vocabulary. I currently have two forms, one for selecting the first letter and one for selecting the part of speech/tag (the facets). class LemmaInitialLetterForm(forms.Form): LETTERS = [ ... ] initial = forms.ChoiceField( widget=forms.RadioSelect( attrs={"class": "lem_init"} ), choices=LETTERS ) class FacetSideBarForm(forms.Form): poss = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, label='Parts of speech', choices=list() ) tags = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, label='Tags', choices=list() ) def __init__(self, poss=None, tag_list=None, *args, **kwargs): super(FacetSideBarForm, self).__init__(*args, **kwargs) if poss: self.fields['poss'].choices = [ (pos, pos) for pos in poss ] if tag_list: self.fields['tags'].choices = [ (tag, tag) for tag in tag_list ] I've been able to display a list of Lemma filtered by first letter with the following view: class LemmaListView(generic.FormView): template_name = "emedict/lemma_home.html" lemmalist = None def get(self, request, *args, **kwargs): form = LemmaInitialLetterForm(self.request.GET or None) if form.is_valid(): initial = request.GET["initial"] … -
Django Simple JWT + Axios, always getting 401. How can I fix this?
I’m using Nuxt and a pinia store to store the token (the token is present in the store). I've created a plugin for Axios as follows: import axios from "axios"; export default defineNuxtPlugin((NuxtApp) => { axios.defaults.baseURL = "http://127.0.0.1:8000/api/"; axios.defaults.withCredentials = false; axios.defaults.proxyHeaders = false; if (process.client) { let token = window.localStorage.getItem("authTokens"); if (token) { token = JSON.parse(token); console.log(token.access); axios.defaults.headers.common["Authorization"] = `Bearer ${token.access}`; } } return { provide: { axios: axios, }, }; }); The endpoint in Django REST Framework is defined like this: class CreateEvent(CreateAPIView): permission_classes = [IsAuthenticated] serializer_class = CreateEventSerializer def post(self, request, *args, **kwargs): data = request.data.copy() z = request.META.get('HTTP_AUTHORIZATION') data['creator'] = request.user print(request.user, '--------------------') data['types'] = get_type_by_int(request.data.get('type', None)) serializer = self.get_serializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) The method I use to call this endpoint is as follows: async sendEvent(): Promise<void> { try { const { $axios } = useNuxtApp(); const response = await $axios.post("event/create/", { latitiude: this.latitiude, longitude: this.longitude, description: this.description, type: this.type, }); console.log("Event sent:", response.data); } catch (error) { console.error("Error while sending event"); } } No matter what I do, I keep receiving a 401 error with the message: Authentication credentials were not provided. However, the z = request.META.get('HTTP_AUTHORIZATION') line contains … -
Importing model classes from other apps in Django with cicular import Problem
Hi i Need to import a model into another app models that will raise the cicular import Error so i use the django.app like this : from django.apps import apps Order = apps.get_model(app_label="orders", model_name='Order') its raise AppRegistryNotReady Error : File "C:\Users\Pourya\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner self.run() File "C:\Users\Pourya\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "C:\Users\Pourya\Desktop\fapo\.venv\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Pourya\Desktop\fapo\.venv\Lib\site-packages\django\core\management\commands\runserver.py", line 126, in inner_run autoreload.raise_last_exception() File "C:\Users\Pourya\Desktop\fapo\.venv\Lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\Pourya\Desktop\fapo\.venv\Lib\site-packages\django\core\management\__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "C:\Users\Pourya\Desktop\fapo\.venv\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Pourya\Desktop\fapo\.venv\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Pourya\Desktop\fapo\.venv\Lib\site-packages\django\apps\registry.py", line 116, in populate app_config.import_models() File "C:\Users\Pourya\Desktop\fapo\.venv\Lib\site-packages\django\apps\config.py", line 269, in import_models self.models_module = import_module(models_module_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Pourya\AppData\Local\Programs\Python\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\Users\Pourya\Desktop\fapo\shop\models.py", line 17, in <module> Order = apps.get_model(app_label="orders", model_name='Order') ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Pourya\Desktop\fapo\.venv\Lib\site-packages\django\apps\registry.py", line 201, in get_model self.check_models_ready() File "C:\Users\Pourya\Desktop\fapo\.venv\Lib\site-packages\django\apps\registry.py", line 143, in check_models_ready raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models … -
Django: No tables found in the database after running migrations
I'm working on a Django project, but I'm facing an issue where no tables are being created in my database even after running migrations. Django version:5.1.3 Database:MySQL OS:ubuntu 24.04.1 LTS 1 I ran python manage.py makemigrations, and it successfully generated migration files 2 I ran python manage.py migrate, and it executed without any errors. 3 However, when I check the database in phpmyadmin, No tables found in database. I also tried these troubleshooting steps: 1 Verified that the database file exists. 2 Ensured that the INSTALLED_APPS list includes my app. 3 Checked that the models are defined properly in the models.py file. 4 Looked for migration history with python manage.py showmigrations, and all migrations are marked as applied. What could be causing this issue? Are there any additional steps I can take to debug or resolve this problem? I’d appreciate any guidance or suggestions. Let me know if more information is needed. -
How do i find "Average Word Count of Comments for Each Blog"?
This is my models: from django.db import models from django.conf import settings from django.utils import timezone class Blog(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return f"{self.title}" class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='comments') blog = models.ForeignKey(Blog, on_delete=models.CASCADE, related_name='comments') comment = models.TextField() published_date = models.DateTimeField(default=timezone.now) def __str__(self): return f"{self.comment}" I tried annotate() using Blog.objects.annotate(avg_comment_length = Avg(Length(comments__comment))) but Length() gets the total characters in a comment, not word count. How can I modify this to calculate the average word count of comments for each blog? -
Error deploying django/python app to Heroku - 'Error with requirements to build wheel'
I am trying to deploy my Django app to Heroku. I get the following error output: Installing build dependencies: started Installing build dependencies: finished with status 'done' Getting requirements to build wheel: started Getting requirements to build wheel: finished with status 'error' error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> [24 lines of output] Traceback (most recent call last): File "/app/.heroku/python/lib/python3.13/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 353, in <module> main() ~~~~^^ File "/app/.heroku/python/lib/python3.13/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 335, in main json_out['return_val'] = hook(**hook_input['kwargs']) ~~~~^^^^^^^^^^^^^^^^^^^^^^^^ File "/app/.heroku/python/lib/python3.13/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 118, in get_requires_for_build_wheel return hook(config_settings) File "/tmp/pip-build-env-zgoqdfmt/overlay/lib/python3.13/site-packages/setuptools/build_meta.py", line 334, in get_requires_for_build_wheel return self._get_build_requires(config_settings, requirements=[]) ~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/tmp/pip-build-env-zgoqdfmt/overlay/lib/python3.13/site-packages/setuptools/build_meta.py", line 304, in _get_build_requires self.run_setup() ~~~~~~~~~~~~~~^^ File "/tmp/pip-build-env-zgoqdfmt/overlay/lib/python3.13/site-packages/setuptools/build_meta.py", line 522, in run_setup super().run_setup(setup_script=setup_script) ~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/tmp/pip-build-env-zgoqdfmt/overlay/lib/python3.13/site-packages/setuptools/build_meta.py", line 320, in run_setup exec(code, locals()) ~~~~^^^^^^^^^^^^^^^^ File "<string>", line 29, in <module> File "<string>", line 26, in get_version KeyError: '__version__' [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> See above for output. note: This error originates from a subprocess, and is likely not a problem with pip. ! Error: Unable … -
AttributeError with User in django application
I am making an app for a clinic. I am in the finance section of my app. I want to make an income through an appointment. When I went to test this endpoint in postman, I get the following error: AttributeError: Got AttributeError when attempting to get a value for field user on serializer UserInfoSerializer. The serializer field might be named incorrectly and not match any attribute or key on the User instance. Original exception text was: 'User' object has no attribute 'user'. I am sending you my files so that you can help me as I have had this error for a couple of days without being able to solve it. userinfo/models.py from django.db import models from django.contrib.auth.models import User class UserInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="userInfo") address = models.CharField(max_length=255, blank=True, null=True) phone = models.CharField(max_length=15, blank=True, null=True) fecha_nacimiento = models.DateField(blank=True, null=True) dni = models.CharField(max_length=10, blank=True, null=True) postal_code = models.CharField(max_length=6, blank=True, null=True) city = models.CharField(max_length=200, blank=True, null=True) country = models.CharField(max_length=100, blank=True, null=True) segundo_apellido = models.CharField(max_length=200, blank=True) def __str__(self): return f"Información de {self.user.username}"` My finanzas/models.py: from django.db import models from citas.models import Citas from userinfo.models import UserInfo class Transaccion(models.Model): INGRESO = 'INGRESO' GASTO = 'GASTO' INGRESO_COTIZADO = 'INGRESO_COTIZADO' TIPO_CHOICES = [ … -
getting started with grpc django throws import error
Sure! Here’s your question formatted according to Stack Overflow standards: Title: gRPC Python Import Error for Generated hello_pb2.py and hello_pb2_grpc.py Files Question: I have a hello.proto file on the server side. On the client side, I ran the following protoc command to generate the necessary Python files: python3 -m grpc_tools.protoc -I. -Iproto-lib/src/main/proto -Iproto-lib/src/main/proto/common --python_out=./publons/scholarly_person_master_service --grpc_python_out=./app proto-lib/src/main/proto/hello.proto This command created two files on the client side: hello_pb2.py hello_pb2_grpc.py I then created a Python script on the client side to use these files and set up a gRPC server. The code looks as follows: import grpc from concurrent import futures from scholarly_person_master_service.sp_master_ri_proto_lib.src.main.proto.hello_pb2 import HelloReply, HelloRequest from scholarly_person_master_service.sp_master_ri_proto_lib.src.main.proto.hello_pb2_grpc import SimpleServicer, add_SimpleServicer_to_server # Implementing the service class SimpleService(SimpleServicer): def SayHello(self, request, context): # This method handles the gRPC call and returns a response response = HelloReply(message=f"Hello, {request.name}!") return response # Running the gRPC server def serve(): server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) add_SimpleServicer_to_server(SimpleService(), server) # Registering the service server.add_insecure_port('[::]:50051') server.start() print("Server started on port 50051") server.wait_for_termination() if __name__ == '__main__': serve() However, when I try to run the server, I encounter an error related to the imports (HelloRequest and HelloReply), even though other imports in the script are working fine. hello_pb2.py File The hello_pb2.py file looks like … -
Django 4 Everybody: 405 Error, Auto-grader assignment Ad List #1
I'm following the DJ4E coursera course and I am on the 5th module auto-grader assignment: Ad List #1 When I run the auto-grader everything passes except the last test and I get this error: Logging out... Loading URL: https://loupy316.pythonanywhere.com/logout/?next=/ads/ (Open URL) Could not find HTML The current node list is empty. Here is my html: {% extends 'base_bootstrap.html' %} {% load app_tags %} <!-- see home/templatetags/app_tags.py and dj4e-samples/settings.py --> {% block navbar %} <nav class="navbar navbar-expand-lg navbar-dark bg-dark" style="border-radius:10px !important"> <div class="container-fluid"> <a class="navbar-brand" href="{% url 'home:home' %}">LP's Site</a> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> {% url 'home:home' as home_url %} <a class="nav-link {% if request.get_full_path == home_url %}active{% endif %}" href="{% url 'home:home' %}">Home</a> {% url 'ads:all' as ads_url %} <li {% if request.get_full_path == ads_url %}class="active"{% endif %}> <a class="nav-link" href="{% url 'ads:all' %}" role="button">Ads</a> </li> </ul> <ul class="navbar-nav"> {% if user.is_authenticated %} <li> <a class="nav-link" href="{% url 'ads:ad_create' %}">Create Ad</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="rightnavDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> <img style="width: 35px; height: 35px; border-radius: 50%; object-fit: cover;" src="{{ user|gravatar:60 }}"/><b class="caret"></b> </a> <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="rightnavDropdown"> <li> <form method="post" action="/admin/logout/?next={% url 'ads:all' %}"> {% csrf_token %} <button type="submit" class="dropdown-item">Logout</button> </form> </li> </ul> </li> {% … -
Django 5.1 UserCreationForm won't allow empty passwords
I am upgrading a Django 3.0 app to 5.1 and have been moving slowly through each minor release. So far so good. However, once I upgraded from Django 5.0 to 5.1, I saw changed behavior on my "Create New User" page, which used to allow empty passwords, with a random password being generated if none is supplied. Now, I can no longer submit an empty password. I get a "required field" error on both the password fields, even though the fields are both explicitly set as required=False. I know there were some changes (5.1.0, 5.1.1) to the UserCreationForm class in Django 5.1. I tried using AdminUserCreationForm instead of UserCreationForm and setting the usable_password field to None, but it still won't allow empty passwords like before. Any ideas? Environment Python 3.12.8 Django 5.1.5 Simplified Code class SignupForm(AdminUserCreationForm): # previously using UserCreationForm usable_password = None # Newly added # Form fields sharedaccountflag = forms.ChoiceField( label='Cuenta compartida', required=True, choices=BOOLEAN_CHOICES ) # Constructor def __init__(self, *args, **kwargs): # Call base class constructor (i.e. SignupForm) super(SignupForm, self).__init__(*args, **kwargs) # Set password fields as optional self.fields['password1'].required=False self.fields['password2'].required=False # Set form helper properties self.helper = FormHelper() setFormHelper(self.helper) # set form method (POST / GET) and styling self.helper.form_tag … -
Using sessions in post requests django
I am currently trying to code my first website. I have a post request taking in answers from a form. I then try to save this information into the session and this doesn’t seem possible. Even when just editing the session data inside the request it doesn’t seem possible and I also can’t print to debug, this could be a stupid question as I am very inexperienced but I cannot find any solution or a reason why? -
Saving "last seen" time doesn't work beyond a few seconds
Based on this question I added the following middleware to track users' last seen date: from datetime import datetime, timedelta from dateutil.parser import parse from .models import User class LastSeenMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): last_seen = request.session.get("last-seen") now = datetime.now() too_old_time = now - timedelta(seconds=60) if not last_seen or parse(last_seen) < too_old_time: if request.user.is_authenticated: User.objects.filter(id=request.user.id).update(last_seen=now) request.session["last-seen"] = now.isoformat() return self.get_response(request) This works when I set the timedelta to only a few seconds, but anything more and it stops updating the field. Am I missing something obvious? -
Setting up Django in a subdirectory
I am trying to set up Django in a subdirectory (running under Apache2 through wsgi), but Django stops recognizing the static URLs. This is an example url, that gives me a 404: https:/<domain>/<subdirectory>/<appname>/en/static//img/favicon.png This should map to the filesystem here: /<projectpath>/<appname>/static/<appname>/img/favicon.png The development server (without a subdirectory) finds the file in the filesystem here: /<appname>/static/<appname>/img/favicon.png How do I setup django to recognize it's not running at / but at /<subdomain>/? -
How to show multiple objects in Django detailview
I have two models created, one Topic and another Entries. Listview showing all the Topics link. Clicking on each topic link will show all the entries related to that particular topic. I have created multiple entries for each Topic. DetailView only showing single entries for each topic link. How to show multiple entries for each topic link using DetailView? Models.py class Topic(models.Model): '''A topic that user will add the content about.''' title = models.CharField(max_length=200) class Entries(models.Model): '''Entries and Topic will have many to one relationship''' topic = models.ForeignKey(Topic, on_delete=models.CASCADE) text = models.TextField() image = models.ImageField(upload_to='images', blank=True) date_added = models.DateTimeField(auto_now_add=True) views.py class TopicListView(ListView): model = Topic template_name = 'cms_app/topic_list.html' context_object_name = 'topic' class ContentDetailView(DetailView): model = Entries urls.py urlpatterns = [ path('', TopicListView.as_view(), name = 'all-topic'), path('content/<int:pk>', ContentDetailView.as_view(), name = 'all-content'), ] Topic.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>All Topics</title> </head> <body> <h1>Topic List</h1> <h3> {% for data in topic %} <p><a href="{% url 'all-content' data.id %}">{{ data.title }}</a></p> {% endfor %} </h3> </body> </html> Entries.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>All Contents</title> </head> <body> <p>{{object.text }}</p> <p>{{object.image }}</p> <p>{{object.date_added }}</p> </body> </html> -
celery-container error (exited with code 1) after installing and adding django-crontab to INSTALLED_APPS in settings.py
I work on a django project, which needs celery for running some tasks in the background. I also need to run some cron-jobs, so I installed django-crontab into the container, added to the INSTALLED_APPS in settings.py, "python manage.py crontab show" OUTPUT: root@865809c7149e:/apps# python manage.py crontab show Currently active jobs in crontab: ab590d03e928be09c5fc1a0048404548 -> ('*/3 * * * *', 'AppName.cron.cron_job_method', '>> /apps/crontab.log') SADLY no crontab.log file appears... I don't understand why... AND: celery container exits on "docker compose up" with: ... celery-1 | ModuleNotFoundError: No module named 'django_crontab' celery-1 exited with code 1 web-1 | Watching for file changes with StatReloader Here my docker-compose.yml services: db: image: postgres:17 env_file: .env volumes: - ./local-db:/var/lib/postgresql/data redis: image: redis:7 web: build: . command: python manage.py runserver 0:8030 ports: - 8030:8030 volumes: - ./projectDIR:/apps env_file: .env links: - db depends_on: - db - redis celery: build: . command: celery -A projectDIR worker -l INFO env_file: .env volumes: - ./projectDIR:/apps environment: redis_url: redis://redis:6379/0 links: - db - redis - web depends_on: - web - redis ANY HELP IS VERY APPRECIATED! -
How can I configure a Django Unfold "custom site" with a required URL parameter?
I'm attempting to create a "custom site" using Django Unfold. I have an existing admin panel configured using the more basic ModelAdmin approach which works nicely. However, I need to create a separate admin panel using the "custom site" feature for use with django-tenants. I want the URL structure to look like: http://localhost:8000/tenant-admin/$tenant-id/. Within the "custom site", Django Tenants will scope the Postgres search path to the correct Postgres schema and the admin will be able to manage all of the models for a given tenant. I have defined my custom site as follows: from django.contrib import admin from django.urls import path from unfold.sites import UnfoldAdminSite from unfold.admin import ModelAdmin from tenant_app.models import Foo class TenantAdminSite(UnfoldAdminSite): # hopefully not needed -- but this is the first instance of admin:index causing problems # index_template = "admin/dashboard.html" def get_app_list(self, *args, **kwargs): # this lives at apps/tenant_app and is the only app that this TenantAdminSite # will use. Not sure if strings are valid here? return ["tenant_app"] def get_urls(self): """ Add custom URLs to the default admin site, capturing the tenant name. """ from django.urls import reverse # Capture the tenant name as part of the URL urls = super().get_urls() # Add custom … -
How to find user_id in Django endpoint
I have this Django endpoint: def get(http_request: HttpRequest, id: str): book_account_id = UUID(id) user_id: UUID = http_request.user.id affiliated_price_subscriptions = None response = BookAccountService.filter( id=book_account_id ).prefetch_related( Prefetch( 'subscription_set', queryset=SubscriptionRepository.filter( active=True ).prefetch_related( Prefetch( 'pricesubscription_set', queryset=PriceSubscriptionRepository.filter( Q(status=PriceSubscription.PriceSubscriptionStatus.PENDING) | Q(status=PriceSubscription.PriceSubscriptionStatus.REQUIRES_PAYMENT) ), to_attr='price_subscriptions' ) ), to_attr='subscriptions' ) ).first() affiliated_price_subscriptions = list(chain.from_iterable( subscription.price_subscriptions for subscription in response.subscriptions )) # The user must be part of the group that owns the book account # or the book acc must have at least one pending subscription if not PersonGroupService.exists( person__user_id=user_id, group__bookaccount__id=book_account_id ) and affiliated_price_subscriptions is None: return RestResponse( status=status.HTTP_200_OK, data=Response( code=24, error=True, messages=[ f"User with ID {user_id} does not have access to book account with ID {book_account_id}." ], data=None, ).to_dict(), ) return (...) Basically what it does is to get the book_account either if: the user.id belongs to a person that belongs to the group of that book_account. The book account has a related a related price-subscription with a PENDING or PENDING_PAYMENT status. I erased the is_authenticated: True since for 2) you do not need to be logged in to obtain the book_account data. However, when I call the endpoint while authenticated I get an error since user_id is null. I realized the only way to not have … -
Django Daphne not working with WSS, Ngnix and Docker
I'm trying to deploy an application built with Django and Daphne to open a WebSocket connection. Everything works perfectly on localhost, as I'm not using Nginx. However, in production, I need to use Nginx to serve SSL/HTTPS connections, including WSS. Unfortunately, it no longer works. When I try to use HTTPS on port 443, the WebSocket connection remains pending indefinitely until it eventually fails. I really considered removing Nginx because I found a Daphne configuration that runs on port 443 with an SSL certificate. daphne -b 0.0.0.0 -e ssl:443:privateKey=/privkey.pem:certKey=/fullchain.pem core.asgi:application However, I would still need Nginx to serve static files. I feel like I've tried everything so far. Can someone help me? docker-compose.yml services: web: build: . container_name: meetlink_django_app ports: - 8000:8000 - 8001:8001 volumes: - .:/app - static_volume:/app/core/staticfiles - ./certbot/conf:/app/certbot/conf:ro - ./certbot/www:/app/certbot/www:ro environment: - DEBUG=True - PYTHONUNBUFFERED=1 - DJANGO_SETTINGS_MODULE=core.settings - ENV=${ENV} networks: - meetlink-network command: - bash - -c - "python manage.py migrate && python manage.py runserver 0.0.0.0:8000 & daphne -b 0.0.0.0 -p 8001 core.asgi:application" depends_on: database: condition: service_healthy cache: condition: service_healthy database: image: postgres container_name: meetlink_django_database environment: - POSTGRES_USER=${DB_USERNAME} - POSTGRES_PASSWORD=${DB_PASSWORD} - POSTGRES_DB=${DB_NAME} ports: - ${DB_PORT}:5432 volumes: - database_volume:/var/lib/postgresql/data networks: - meetlink-network healthcheck: test: ["CMD-SHELL", "pg_isready -U $$POSTGRES_USER"] … -
500 server error with Django Rest Framework
I am using Django/DRF with Djoser and djangorestframework-simplejwt to create an API for full authentication including signup, login, activation, forgot password and reset password. I followed along with this YT tutorial For some reason, when I send a POST request in Postman to localhost:8000/api/users/ I am getting this error and I have no idea why at this point, django.db.utils.DatabaseError: Save with update_fields did not affect any rows. I'm not using SQLite but an actual Postgres db on localhost. I've tried changing user.save(self._db) to just user.save(), same error. I've updated Django to 5x. Django is the only one with a significant update compared to the tutorial, he uses Django 4x. I did move some of the original model code to a managers.py file based on this testdriven.io tutorial I've been able to run python manage.py runserver with no errors after doing so. It doesn't seem to be any code related to the tutorial but something with the python packages... Here is the error from the cli: [24/Jan/2025 16:40:07] "POST /api/users/ HTTP/1.1" 500 138392 Bad Request: /api/users/ [24/Jan/2025 17:05:47] "POST /api/users/ HTTP/1.1" 400 62 Internal Server Error: /api/users/ Traceback (most recent call last): File "/home/da/projects/full_auth_api/full_auth/backend/venv/lib/python3.12/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) … -
Puppeteer not working with Django Viewset
I am trying to write a Django REST endpoint which will convert the HTML content to PDF and then return the Streaming file response to download the report. For this purpose, I am using Puppeteer, which works fine out of Django scope (e.g. for testing purpose). The download view minimal example is following import asyncio from pyppeteer import launch from django.http import HttpResponse from rest_framework.viewsets import ViewSet from rest_framework.permissions import IsAuthenticated from rest_framework_simplejwt.authentication import JWTAuthentication class DownloadReport (ViewSet): permission_classes = [IsAuthenticated] authentication_classes = [JWTAuthentication] async def html_to_pdf(self, html): browser = await launch( headless=True, args=['--no-sandbox', '--disable-setuid-sandbox'] ) page = await browser.newPage() await page.setContent(html) await page.setViewport({ 'width': 1920, 'height': 1080, 'deviceScaleFactor': 1 }) pdf = await page.pdf({ 'format': 'A3', 'printBackground': True, 'landscape': True, 'scale': 1 }) await browser.close() return pdf def retrieve(self, request): content = "<h1>Hurrah PDF conversion successfull<h1>" content = asyncio.run(self.html_to_pdf(content)) response = HttpResponse(content, content_type='application/pdf') response['Content-Disposition'] = f'attachment; filename="report.pdf"' return response The problem is in Djanog the browser is neven launched it thrwos following exeption Traceback (most recent call last): File "C:\Users\Zain ul abdin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\Zain ul abdin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Zain ul abdin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\decorators\csrf.py", line 65, in … -
FormData file upload to Django model?
I'm trying to upload a file through a jQuery ajax request, using FormData. When I set processData and contentType to false, I get the error Forbidden (CSRF token missing.). When I remove those, I get the error Uncaught TypeError: 'slice' called on an object that does not implement interface Blob.. What am I missing here? $(".form").on("submit", function(event) { event.preventDefault(); $.ajax({ url: "/upload_profile_pic/", type: "POST", data: { "profile_pic": formData.get("file"), "csrfmiddlewaretoken": $(this).find("input[name='csrfmiddlewaretoken']").val() }, }, success: function (data) { console.log("success: "+data); }, error: function (data) { console.log(data); } }); }); -
Django vs PHP 8.*: Memory usage with 1000 concurrent visitors
I'm currently deciding between Django (Python) and PHP 8.* for a very large project that expects high traffic. Memory usage is a crucial factor for me since the website will need to handle a significant number of concurrent visitors. For example, let's say the site needs to handle 1000 concurrent visitors. Please consider that the project will be well optimized. From what I understand: PHP creates a new process for each request, which might lead to higher memory consumption under heavy load since each request is handled separately. Django, on the other hand, uses a persistent process to handle requests, which might help with better memory management but could also cause its own memory-related concerns under high traffic. I've asked ChatGPT for advice on this, but it gives random and wrong answers, so I don't trust it. I'm looking for insights or benchmarks that compare the memory usage of PHP and Django when handling high traffic and concurrent users. Specifically, how much memory each might use when handling around 1000 concurrent visitors, and any research on how each stacks up in terms of scalability and memory efficiency. Which language/framework would you recommend if memory usage is a key factor for … -
Arrows in Maplibre
Hey I am using maplibre for custom map, i am using geodjango for backend, data coming from database is { id: "arrow_tile_layer", type: "symbol", source: "arrow", 'source-layer': "line", minzoom: 16, maxzoom: 20, filter: ["==", ["get", "way_type"], "primary"], paint: {'text-color': '#000000', 'text-opacity': 0.8}, layout: {'text-font': ['Noto Sans Regular'], 'text-size': 12, 'text-field': '- > ', 'symbol-placement': 'line'}, } there isn't any error in the frontend however, in the map arrows is not visible I have tried to show the arrows in highway, but it is not visible -
"Token contained no recognizable user identification" when refreshing access token
i have the following setup for logging user in and giving out the access and refresh token, refresh token is set in cookies and the access_token is just handed out in json # login_views class UserLoginAPIView(APIView): class UserLoginInputSerializer(serializers.Serializer): username_or_email = serializers.CharField(write_only=True) password = serializers.CharField(write_only=True) class UserLoginOutputSerializer(serializers.Serializer): username = serializers.CharField(read_only=True) user_email = serializers.EmailField(read_only=True) full_name = serializers.CharField(read_only=True) is_verified = serializers.BooleanField(read_only=True) verification_required = serializers.BooleanField(read_only=True) user_type = serializers.ListField(child=serializers.CharField(), read_only=True) staff = serializers.BooleanField(read_only=True) superuser = serializers.BooleanField(read_only=True) access_token = serializers.CharField(read_only=True) def post(self, request, *args, **kwargs): input_serializer = self.UserLoginInputSerializer(data=request.data) input_serializer.is_valid(raise_exception=True) try: login_details, refresh_token = user_login( **input_serializer.validated_data ) except DjangoValidationError as e: return Response( { "success": False, "message": e.message, }, status=status.HTTP_401_UNAUTHORIZED, ) except ValidationError as e: return Response( { "success": False, "message": e.detail[0], }, status=status.HTTP_401_UNAUTHORIZED, ) except Exception as e: return Response( { "success": False, "message": str(e), }, status=status.HTTP_400_BAD_REQUEST, ) output_serializer = self.UserLoginOutputSerializer(login_details) response = Response( { "success": True, "message": "User log in successful.", "data": output_serializer.data, }, status=status.HTTP_200_OK, ) response.set_cookie( "refresh_token", refresh_token, max_age=settings.REFRESH_COOKIE_MAX_AGE, httponly=True, samesite="none", secure=False, ) return response def user_login(*, username_or_email: str, password: str) -> tuple: """ Verifies user's credentials & returns access token & refresh token. """ @dataclass(frozen=True) class UserLoginDetails: user_type: List[str] username: str user_email: str full_name: str is_verified: bool access_token: str staff: bool superuser: bool …