Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django jwt token error with react. "Given token not valid for any token type, token_not_valid"
I am using Django Rest Framework for authentication and Axios in the frontend(reactjs). Everything was working fine while development and then tested on a test server at my company and jwt was working fine, when deployed to the production server I randomly get the following error : { "detail": "Given token not valid for any token type", "code": "token_not_valid", "messages": [ { "token_class": "AccessToken", "token_type": "access", "message": "Token is invalid or expired" } ] } Sometimes I get this error in the first API call after login, some other time I get it after sending multiple requests after login, also I never get it through postman I am will list my nginx conf and my react config nginx: upstream api { server ${DJANGO_API}; } server { listen 80 default_server; server_name xx; server_tokens off; add_header X-Frame-Options "DENY"; proxy_cookie_flags one samesite=strict; client_max_body_size 10M; location /api/ { proxy_pass http://api$request_uri; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /admin/ { proxy_pass http://api$request_uri; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /swagger/ { proxy_pass http://api$request_uri; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /redoc/ { proxy_pass http://api$request_uri; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /staticfiles/ { … -
cannot install latest mysqlclient on ubuntu
I have read pip install mysql-python fails with EnvironmentError: mysql_config not found and mysql_config not found when installing mysqldb python interface and I am sure it is not a duplicate question. I had run sudo apt-get install python3-dev default-libmysqlclient-dev build-essential pkg-config and I have those build tools. I have mariadb installed. I also tried a different pypi mirror and the issue presists. Now I tried pip install mysqlclient and I got this. It seemed that pip is trying through versions. Finally I installed version 2.1.1 Collecting mysqlclient Using cached https://mirrors.tuna.tsinghua.edu.cn/pypi/web/packages/7d/62/51fbcd851834c830c940ded80280f593bd031137603329dd89479c68c5be/mysqlclient-2.2.6.tar.gz (91 kB) Installing build dependencies ... done Getting requirements to build wheel ... done Installing backend dependencies ... done Preparing metadata (pyproject.toml) ... done WARNING: Generating metadata for package mysqlclient produced metadata for project name unknown. Fix your #egg=mysqlclient fragments. Discarding https://mirrors.tuna.tsinghua.edu.cn/pypi/web/packages/7d/62/51fbcd851834c830c940ded80280f593bd031137603329dd89479c68c5be/mysqlclient-2.2.6.tar.gz#sha256=c0b46d9b78b461dbb62482089ca8040fa916595b1b30f831ebbd1b0a82b43d53 (from https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple/mysqlclient/) (requires-python:>=3.8): Requested unknown from https://mirrors.tuna.tsinghua.edu.cn/pypi/web/packages/7d/62/51fbcd851834c830c940ded80280f593bd031137603329dd89479c68c5be/mysqlclient-2.2.6.tar.gz#sha256=c0b46d9b78b461dbb62482089ca8040fa916595b1b30f831ebbd1b0a82b43d53 has inconsistent name: filename has 'mysqlclient', but metadata has 'unknown' Using cached https://mirrors.tuna.tsinghua.edu.cn/pypi/web/packages/be/95/1af2ee813d4f0b607082c18bb82aa05c98a95a402a1d2d5808999317cb16/mysqlclient-2.2.5.tar.gz (90 kB) Installing build dependencies ... done Getting requirements to build wheel ... done Installing backend dependencies ... done Preparing metadata (pyproject.toml) ... done WARNING: Generating metadata for package mysqlclient produced metadata for project name unknown. Fix your #egg=mysqlclient fragments. Discarding https://mirrors.tuna.tsinghua.edu.cn/pypi/web/packages/be/95/1af2ee813d4f0b607082c18bb82aa05c98a95a402a1d2d5808999317cb16/mysqlclient-2.2.5.tar.gz#sha256=add8643c32f738014d252d2bdebb478623b04802e8396d5903905db36474d3ff (from https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple/mysqlclient/) (requires-python:>=3.8): Requested unknown from … -
Django Unknown fields FieldError in forms.py with nested User model
Okay so this is a Django project I'm starting, and I have a User model in models.py. It has nested models, the 'contact' model and the 'personal' model. I want to create a form in Django. models.py class User(models.Model): """ Model representing a User with field groups """ class ContactInfo(models.Model): email = models.EmailField( max_length=120, validators=[EmailValidator()], unique=True, verbose_name="Contact Email" ) phone = models.CharField( max_length=10, blank=True, null=True, verbose_name="Phone Number" ) address = models.CharField( max_length=100, validators=[MinLengthValidator(5)], verbose_name="Address" ) suite = models.CharField( max_length=20, validators=[MinLengthValidator(0)], verbose_name="Suite" ) city = models.CharField( max_length=50, validators=[MinLengthValidator(3)], verbose_name="City" ) state = models.CharField( max_length=2, validators=[MinLengthValidator(2)], verbose_name="State" ) zip_code = models.CharField( max_length=5, validators=[MinLengthValidator(5)], verbose_name="Zip Code" ) class PersonalInfo(models.Model): first_name = models.CharField( max_length=40, validators=[MinLengthValidator(2)], verbose_name="First Name" ) last_name = models.CharField( max_length=40, validators=[MinLengthValidator(2)], verbose_name="Last Name" ) company = models.CharField( max_length=100, validators=[MinLengthValidator(5)], verbose_name="Company Name" ) contact = models.OneToOneField( ContactInfo, on_delete=models.CASCADE, related_name='user_contact' ) personal = models.OneToOneField( PersonalInfo, on_delete=models.CASCADE, related_name='user_personal' ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.personal.first_name} {self.personal.last_name}" forms.py from django import forms from .models import User, Request class UserForm(forms.ModelForm): """ Form for users """ class Meta: model = User fields = ( 'personal.first_name', 'personal.last_name', 'personal.company', 'contact.email', 'contact.phone', 'contact.address', 'contact.suite', 'contact.city', 'contact.state', 'contact.zip_code', ) def save(self, commit=True): user = super().save(commit=False) contact_info, _ = … -
Python unittest.mock patch fail with F() expressions can only be used to update, not to insert
A minimal working example is available at https://github.com/rgaiacs/django-mwe-magicmock. When using Django, I use Model.clean() to validate the form submitted by the user. During the validation, some fields might be updated based on the response of a HTTP request. I want to test the Model.clean() using Python's unittest and mocking the HTTP request. My app/models.py is import logging from django.core.exceptions import ValidationError from django.db import models from .aid import GitHosting logger = logging.getLogger(__name__) class Resource(models.Model): code_repository = models.URLField( help_text="Link to the repository where the un-compiled, human readable code and related code is located." ) version = models.CharField( blank=True, # Git hash contains 40 characters max_length=50, default="HEAD", help_text="The version of the resource in the format of a Git commit ID or Git tag.", ) def clean(self): git_host = GitHosting() self.version = git_host.get_version() and my app/tests.py is import logging from unittest.mock import patch from django.test import TestCase from django.urls import reverse from .models import Resource logger = logging.getLogger(__name__) @patch("app.models.GitHosting.get_version") class ResourceViewTestCase(TestCase): def test_add_resource(self, mock_get_version): mock_get_version = "5678" logger.error("Submitting form ...") response = self.client.post(reverse("app:index"), { "code_repository": "http://mygit.com/foo/bar" }) resource = Resource.objects.get(id=1) self.assertEqual(resource.version, "5678") When I run python manage.py test, the test fail with ValueError: Failed to insert expression "<MagicMock name='get_version().resolve_expression()' id='139668720464128'>" on app.Resource.version. F() … -
automatically backing up the last entry to a field in django admin
I have a model that serves as a price database for a part: class Part(models.Model): name = models.CharField("name", max_length=128) class Price(models.Model): value = models.DecimalField(max_digits=10, decimal_places=2) part = models.ForeignKey(Part, on_delete=models.CASCADE) is_active = models.BooleanField(default=True) in the admin I want to have a field that can change the price, but also a list where the old prices are visible. I kind of solved it with Django built in methods, but it seems rather complicated for such a simple request: class FakePlainTextWidget(forms.Widget): """ this widget masks an input field for prices so they are only being listed and not really editable or look that way """ def __init__(self, attrs=None): super().__init__(attrs) def render(self, name, value, attrs, renderer=None): s = f"""border: none; background-color: transparent; pointer-events: none; -webkit-appearance: none; -moz-appearance: textfield;""" return format_html(f"""<input type="number" name="{attrs["id"][3:]}" value="{value}" id="{attrs["id"]}" style="{s}"> €""") class PriceInlineForm(forms.ModelForm): class Meta: model = Price fields = "__all__" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.instance and not self.instance.is_active: # make fields read-only if price is_active=False for field in self.fields: self.fields[field].widget = FakePlainTextWidget() def save(self, commit=False): instance = super().save(commit=False) instance.is_active = False instance.save(update_fields=["is_active"]) Price.objects.create(value=self.cleaned_data["value"], part=instance.part) return instance class PriceInline(admin.TabularInline): model = Price can_delete = False exclude = ["is_active",] extra = 0 # No extra empty forms … -
My Django project settings seem to form an error
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/Billing/ Using the URLconf defined in eCommerce.urls, Django tried these URL patterns, in this order: admin/ The current path, Billing/, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. This is shown when I tried to create an app using django Here is the code for the program main.urls from django.contrib import admin from django.urls import path, include from BillingST.eCommerce.Billing import views urlpatterns = [ path("admin/", admin.site.urls), path("Billing/", include('Billing.urls')), path('', views.access, name='access') ] billing.urls from django.contrib import admin from django.urls import path, include urlpatterns = [ path('Billing/', include('Billing.urls')), path('admin/', admin.site.urls), ] I was trying to run the code for billing page, but it says to navigate to admin -
Partially initialized module 'pyairtable'
Basically I am bulding a sort of database manager on DJango for the place I work for. I am trying to use airtable as the database (Instead of a JSON or other methods) because we have all the information there. But everytime I try to run the script, it gives me this error AttributeError: partially initialized module 'pyairtable' from 'C:\Users\PC\AppData\Local\Programs\Python\Python313\Lib\site-packages\pyairtable\__init__.py' has no attribute 'api' (most likely due to a circular import). I have the propper packages installed, and I tried looking for a file with the same name that could cause this error, but I found nothing. To test it I even did this script for python and it still does not work from pyairtable import Table from dotenv import load_dotenv, find_dotenv AT = os.getenv(AIRTABLE_TOKEN) BI = os.getenv(BASE_ID) RC_table = Table(AT, BI, 'RC') LB_table = Table(AT, BI, 'L&B') PM_table = Table(AT, BI, 'PM') print("Table imported and initialized successfully!") And it still gives me the same error, I have tried to get the token by pasting it directly on the app and then using the os.getenv() (the token has access to do everything on the airtable tables). I don't know what to do to make it work. -
Best practices for API update and deployment in an existing Django project
Our existing Django project with a couple of apps has new API requirement. I'm thinking of the possibility to deploy the new restful API in a separate wsgi server so the API service will be independent from the orignal Django project. I can see two options: Create new API project which will inherit models and auth. This allows semi-independent update and deployment on the production. Or just create new app in the same project, but use another wsgi server with separate settings. While I'm writing this down I'm already having other insights (magic of writing thoughts), but the objective is to have the API updated and deployed without penalize the availabilty of the existing apps. -
How to integrate the Clover payment gateway using Python?
I’m currently working on integrating the Clover payment gateway in a Python application, but I’m facing some challenges. I’ve reviewed the Clover API documentation and attempted to set up the necessary authentication and API calls, but I’m not sure if I’m following the best practices or missing any key steps. Could anyone with experience in integrating Clover provide guidance, examples, or point me to relevant resources? Here’s what I’ve tried so far: Configured OAuth authentication and fetched some details including Merchant Id, Employee Id, Access Token. We are trying to integrate the payment gateway when a user submits a form. Is there any sample code or any tutorials related to this? Any details would be helpful. -
Selenium doesn't use testing database during Django functional tests in Docker or cannot access container because of port issues
Issue My Selenium Chrome Browser cannot access my Django web application when it uses Djangos test database: host_ip = socket.gethostbyname(socket.gethostname()) host_port = urlparse(self.live_server_url).port self.live_server_url = f"http://{host_ip}:{host_port}" # results in # selenium.common.exceptions.WebDriverException: Message: unknown error: net::ERR_CONNECTION_REFUSED Djangos StaticLiveServerTestCase creates random ports when creating test databases. With docker I can only expose hard coded ports. I can set one fixed port on my tests. But then they complain, that the port is already taken. class FunctionalTest(StaticLiveServerTestCase): """Functional Testing base class.""" port = 50500 # resulsts in: # OSError: [Errno 98] Address in use The other option I thought of was to set the URL for Selenium to my running web application, but than the test database created by StaticLiveServerTestCase won't be used. Instead it uses the postgres container, where objects created in the setup phase cannot be found. In my example test the user cannot login, because the Selenium access a version of the application serving the postgres db instead of the testing db. self.live_server_url = "http://web:8000" # results in # AssertionError: 'Profile' not found in 'Sign In' # the surrounding code is setup correctly, so this normally results in success. Setup I try to create a pipeline for my test driven … -
Django model has ManyToMany field, how to get all IDs without fetching the objects?
I have a data structure like this: class Pizza(models.Model): name = models.CharField(max_length=100) toppings = models.ManyToManyField(Topping, related_name="pizzas") class Topping(models.Model): name = models.CharField(max_length=100) And to get all topping IDs related to a pizza I can do this: list(map(lambda t: t.id, pizza.toppings.all())) But this fetches all toppings completely from the database, even thought I only need the IDs. Is there a way to get the IDs without fetching the complete objects (for performance reasons)? -
How to use Django {% querystring %} with GET form?
In Django 5.1 {% querystring %} was added. Is there some way to use it with GET form? For example, let's say we have template with: <span>Paginate by:</span> <a href="{% querystring paginate_by=50 %}">50</a> {# ... #} <form method="GET"> <input name="query" value="{{ request.GET.query }}"> <button type="submit">Search</button> </form> Assuming that we are currently on localhost:8000/?paginate_by=50, how to change form so clicking Search won't delete paginate_by query parameter - so what I want is for example localhost:8000/?paginate_by=50&query=abc and not localhost:8000/?query=abc? Before 5.1 I handled that via providing form with hidden fields based on GET parameters, but I am hoping that now more elegant solution is possible. -
VS Code does not forward ports (Dev Containers)
I'm currently trying to put my Django application into a dev container. And in itself it does work, but however, I cannot access the page in my browser. I'm using this Tutorial. ./backend/Dockerfile FROM python:3.12 EXPOSE 8000 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 RUN pip install uv COPY pyproject.toml uv.lock ./ RUN uv sync && uv lock WORKDIR /app COPY . /app RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser /app USER appuser CMD [ "uv", "run", "python", "manage.py", "runserver", "0.0.0.0:8000" ] ./docker-compose.yml name: experiments-graphql services: django: image: backend build: context: ./backend dockerfile: ./Dockerfile ports: - 8000:8000 ./.devcontainer/devcontainer.json { "name": "Existing Docker Compose (Extend)", "dockerComposeFile": [ "../docker-compose.yml", "docker-compose.yml" ], "service": "django", "workspaceFolder": "/workspace", "customizations": { "vscode": { "settings": {}, "extensions": [ "ms-python.python", "eamodio.gitlens", "editorconfig.editorconfig" ] } } } ./.devcontainer/docker-compose.yml services: django: volumes: - .:/workspace:cached command: /bin/sh -c "while sleep 1000; do :; done" -
Why is my WebSocket connection being rejected with "Unauthenticated user" in Django Channels even with a valid JWT token?
I am working on a real-time chat application using Django Channels and WebSockets. I have implemented a custom user authentication system using JWT tokens and attached the token-based authentication to the WebSocket connection using Django Channels middleware. However, my WebSocket connection is always being rejected with the message: "Unauthenticated user attempted to connect.", despite sending a valid JWT token in the Authorization header. Here is the relevant code and setup for my project: Project Setup: Django Version: 4.1.4 Django Channels Version: 4.0.0 ASGI Server: Daphne Custom User Model: BasicUserProfile (which stores the JWT token in the auth_token field) Code: 1. CustomAuthMiddleware - Middleware for JWT Authentication: import jwt from datetime import datetime from channels.middleware.base import BaseMiddleware from authentication.models import BasicUserProfile from django.contrib.auth.models import AnonymousUser from django.conf import settings from channels.db import database_sync_to_async class CustomAuthMiddleware(BaseMiddleware): async def populate_scope(self, scope): user = scope.get('user', None) if user is None: token = self.get_token_from_headers(scope) if token: user = await self.get_user_by_token(token) else: user = AnonymousUser() scope['user'] = user def get_token_from_headers(self, scope): headers = dict(scope.get('headers', [])) token = headers.get(b'authorization', None) if token: token_str = token.decode() if token_str.startswith("Bearer "): return token_str[len("Bearer "):] return None @database_sync_to_async def get_user_by_token(self, token): try: decoded_token = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"]) if decoded_token.get('exp') and decoded_token['exp'] … -
Django/html mp3 autoplay
I've got django application, and one view, that checks some data, and passess "play" variable to the template. If play is true - short mp3 "bing" should be played, else, it is not played. The page reloads every 10 seconds, to call view, checks if 'play' changed, and make sound possibly. The problem is, that just after first page load, nothing is autoplayed. I need to click play button on html player one time, and after that, everything works perfectly. But without this first "manual play", it is not working. Any ideas? The django template code is as follows. <html> <head> <script> window.onload = function() { var context = new AudioContext(); } function autoRefresh() { window.location = window.location.href; } setInterval('autoRefresh()', 10000); </script> </head> <body> {%if play%} <audio autoplay controls id="music" > <source src="{%static 'app1/stat1/d.mp3'%}" type="audio/mpeg"> </audio> {%endif%} </body> </html> -
Migration in different schemas of database in Python Django 5
I have a problem to make migrations in PostgreSQL database with 2 schemas: public and users. I have models for users and their profiles. It requires to put them on schema with name "users" and then create superuser and some basic users. But every time when I do migrations, Django creates tables in default schema "public" or I have different mistakes. Many attempts to fix this didn't get me a result, so I need help. My models: class MyUser(AbstractUser): class Meta: managed = True db_table = 'users\".\"user' # gives a problem email = models.EmailField(_("email address"), unique=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["username"] objects = MyUserManager() class MyProfile(models.Model): class Meta: managed = True db_table = 'users\".\"profile' # gives a problem user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=200, default="Name") surname = models.CharField(max_length=200, default="Surname") My Manager: class MyUserManager(BaseUserManager): def create_user(self, email, password, **extra_fields): if not email: raise ValueError(_("Email required")) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault("is_staff", True) extra_fields.setdefault("is_superuser", True) extra_fields.setdefault("is_active", True) if extra_fields.get("is_staff") is not True: raise ValueError(_("is_staff=True required")) if extra_fields.get("is_superuser") is not True: raise ValueError(_("is_superuser=True required")) return self.create_user(email, password, **extra_fields) My DB: 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': "djangotest", 'USER': "postgres", 'PASSWORD': "********", … -
Issue with Testing UpdateView in Django
I have an UpdateView that allows editing objects of the Scooter model. After successfully processing the form (via a POST request), the view is supposed to redirect the user to the detail page of the edited scooter (with a 302 status code). However, in my test, I see that the response after the POST request returns a 200 status code, and response.context contains the object data, as if the form was re-rendered instead of a redirect occurring. Why does the UpdateView return a 200 status code after the POST request, even though the get_success_url method is correctly configured? Is using response.context after POST appropriate in such a test? Should I instead use refresh_from_db for the object in the database? Is there a better way to test UpdateView behavior in Django to avoid potential inconsistencies with the view's behavior after a POST request? (these are in different files ofc, i just needed to paste it here) @pytest.mark.django_db def test_scooter_detail_edit_data(client, superuser_user, available_scooter): url = reverse('scooter-update', kwargs={'scooter_id': available_scooter.id}) client.force_login(superuser_user) response = client.get(url) assert response.status_code == 200 assert response.context['scooter'].available == True assert response.context['scooter'].daily_price == 100 response = client.post(url, data={ 'available': False, 'daily_price': 200, }) assert response.status_code == 200 assert response.context['scooter'].available == False assert response.context['scooter'].daily_price … -
How to highlight all the streets within a range of coordinates of a specific city (eg. Milan) using polyline (Leaflet)?
I want to use overpass API (OpenStreetMapAPI) to fetch the coordinates(longitude and latitude: start, midpoint, end) of all the streets(with specific addresses) within the coordinate range of a specific city(eg. Milan). Can you recommend any documentation or tutorials for this? -
Using AG-grid community addition in offline mode
I am adding Ag-grid community addition (plain java script version) into my django/python app. i was able to make inline editing and other cool free features work by inserting into my base.html. Now, i was asked to copy that js into the repository so that it will work when/if we don't have internet. I copied the content of "https://cdn.jsdelivr.net/npm/ag-grid-community/dist/ag-grid-community.min.js" into my static/js folder and called it ad-grid-community.min.js, so now my base.html file has this link instead: However, now a lot of inline-editing features in my ag-grid table stopped working. I am guessing i need to install additional modules, but how do i do that? Thanks a lot in advance! -
Why does Django show 'using password: NO' error despite correct database credentials?
I'm experiencing an issue with my Django project where logging in produces the following error: Error: (1045, "Access denied for user 'jdcbde5_vawcdb'@'localhost' (using password: NO)") Error: Details: Deployed Project: https://jdcbdev.website/ at inmotionhosting The database credentials in my Django settings (settings.py) are correct. Here's a snippet: I confirmed that NAME and USER are the same with correct password. With correct grants: I wrote a standalone Python script using mysqlclient to connect to the database, and it works without any issues: What could cause Django to fail with this error despite the credentials being correct? Is there something specific about Django's handling of database connections that I might be missing? Thanks in advance for your help! -
Paste object data into admin form
Need help. I have an object that I add using the standard administration form by link /admin/tasklist/task/add/ model.py class Task(models.Model): name = models.CharField("Name", max_length=100) discr = models.CharField("Discription", max_length=255) date = models.DateField("Date") status = models.IntegerField("Status", default=2) def __str__(self): return self.name def natural_key(self): return (self.name) class Meta: db_table = 'tasks' verbose_name = 'Task' verbose_name_plural = 'Tasks' I want to be able to copy an object after making edits from the same admin form. I need that when clicking on the link /admin/tasklist/task/1/copy, the form for adding an object opens, and data from object 1 is inserted into the status and date fields. Maybe I need to create one Custom Admin Actions for this? -
How Do I Set Up WebSockets for a Real-Time Chat App Using Django Channels and React?
I’m working on a real-time chat application with Django Channels on the backend and React on the frontend. My goal is to enable users to exchange messages in real time, but I’m having trouble connecting everything properly. Here’s a rundown of what I’ve done so far: Backend (Django) I’ve set up Django Channels with WebSocket support. This is what my asgi.py file looks like: import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from channels.auth import AuthMiddlewareStack import chat.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings') django_asgi_app = get_asgi_application() application = ProtocolTypeRouter({ "http": django_asgi_app, "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns ) ) ), }) Here’s my WebSocket routing setup in routing.py: from django.urls import path from . import consumers websocket_urlpatterns = [ path('ws/chat/<str:chatgroup_name>', consumers.ChatConsumer.as_asgi(),), ] The consumer (ChatConsumer) handles WebSocket connections and message broadcasts. Here’s a simplified version of it: class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.chatgroup_name = self.scope['url_route']['kwargs']['chatgroup_name'] self.user = self.scope['user'] await self.channel_layer.group_add(self.chatgroup_name, self.channel_name) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard(self.chatgroup_name, self.channel_name) async def receive(self, text_data): message = json.loads(text_data)['body'] await self.channel_layer.group_send( self.chatgroup_name, { 'type': 'chat_message', 'message': message, } ) async def chat_message(self, event): await self.send(text_data=json.dumps(event)) and this is the messages page in the react app: import { useState, useEffect, … -
How to mock a function in a django custom command?
How can I mock foo in order to have it NOT called? Here's my latest attempt: #~/django/myapp/management/commands/acme.py def foo(): pass class Command(BaseCommand): def handle(self, *args, **options): foo() #~/django/myapp/tests/test.py from django.core.management import call_command @mock.patch('myapp.management.commands.acme.foo') def test_command_output(self,mock_foo): call_command('acme') assert not mock_foo.called -
Pre-fetching huge querysets in django
TLDR: how can I prevent very large IN sets in the SQL query generated? When I pre-fetch a ManyToMany field pointing to model Tag from a model Object: obj_qs = models.Object.objects.filter(created_time__gt = 2024) obj_qs.prefetch_related('tags') I get a pre-fetching SQL query of the following form: SELECT (`main_object_tag`.`object_id`) AS `_prefetch_related_val_object_id`, `main_tag`.`id`, `main_tag`.`name` FROM `main_tag` INNER JOIN `main_object_tag` ON (`main_tag`.`id` = `main_object_tag`.`tag_id`) WHERE `main_object_tag`.`object_id` IN (1, 2, 3, 4, 5); args=(1, 2, 3, 4, 5) The problem is, the IN clause could be huge this way - hundreds of thousands of objects in my case. Could I work around this somehow - using a query instead of the "IN" specification? Extra: why? We would serialize the objects in the following way subsequently: return JsonResponse([ { 'name': obj.name, 'tags': [tag.name for tag in obj.tags.all()] } for obj in obj_qs ]) -
Django MySQL and CONVERT_TZ
I need to know the duration of some events in my MySQL database. Around DST the duration in UTC is different then in local time and I need to know them in local time. I have found a way to do this, but I was wondering if this function can be improved. from django.db.models import ExpressionWrapper, F, fields from django.db.models.functions import Cast from django.db.models.expressions import RawSQL duree = ExpressionWrapper(F('_dtend') - F('_dtstart'), output_field=fields.DurationField()) event_dur = Event.objects.annotate( _dtstart=Cast( RawSQL("CONVERT_TZ(dtstart, 'UTC', timezone)", ()), fields.DateTimeField() ), _dtend=Cast(RawSQL("CONVERT_TZ(dtend, 'UTC',timezone)", ()), fields.DateTimeField()), ).annotate( dur=duree ) Without the convert_tz I find 8000 events, with only 1000. There are probably 7000 events around DST last October. So the duration works fine. Great. Problem solved. However, if I do: event_dur.first()._dtstart, event_dur.first().dtstart I get back: datetime.datetime(2024, 11, 22, 0, 0, tzinfo=datetime.timezone.utc), datetime.datetime(2024, 11, 21, 23, 0, tzinfo=datetime.timezone.utc) As you can see the _dtstart (which uses Europe/Amsterdam btw) has the correct time, but the tzinfo is wrong (should be 'Europe/Amsterdam'). While for the duration this is no big problem I was wondering if there is a way to also include the correct timezone information directly out of the database?