Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SSL issue in django web application
I am working on a django web application in python and I use docker containers. My ssl certificate has expired and I want to get a signed certificate from a domain such as go daddy. I tried to use a self signed certificate but I am not able to redirect the website to https. Even though I added reverse proxy in my nginx.conf file to listen to port 80 and 443. Has anyone worked on this before and I will share more details on the same. i have this in my app.conf file server { listen 80; server_name appliication.com www.application.com Ip address 0.0.0.0; location /.well-known/acme-challenge/ { root /var/www/certbot; } location / { return 301 https://$host$request_uri; } } server { listen 443 ssl; server_name appliication.com www.appliication.com Ip address 0.0.0.0; ssl_certificate /etc/path to key; #.crt ssl_certificate_key /etc/path to key; #.pem location / { proxy_pass http://backend:8000; #for demo purposes } } in my docker-compose.yml file I have the below code services: nginx: image: nginx ports: - "80:80" - "443:443" volumes: - ./app.conf:/etc/nginx/conf.d/default.conf - /path/to/your/certificate.pem:/etc/ssl/certs/your_certificate.pem - /path/to/your/private.key:/etc/ssl/private/your_private.key i am not sure where I am going wrong. can anyone help with this -
Django with crisp_forms and django_filters
I want to build a form to create a database object instance using the crispy Layout object. I need a Django filter which appears between the 2 radios (Article List and Category List) and the categories listboxes (see mock below). The 2 filters (Name and Level) should filter the available categories. So, I need a GET form (for the filters) inside the POST form (to create the database object). Any idea how to solve this with crispy? Thanks! -
Execute raw SQL before each select for specific model
I have a complicated report in Django, which is written as raw SQL, and than stored in the database as a database view. I have a Django model (managed=False), tied to that database view, so that I can utilize the django ORM and django rest framework, on top of the database view. This practice is something that I have used on several projects, and works fine. For one specific report, I found that I need to meddle with the postgres query planner, to get it running faster. Before each SELECT statement on that model (database view), to get the SQL to run faster, I need to do: SET enable_nestloop TO off; The query is quite complex, with aggregate functions, and joins on subqueries, so I gave up on trying to optimize it. Turning off the nestloop solves all my performance issues, and I am fine with that, as long as I turn it on back after the query. Here is an explanation of the problem and the solution. (What are the pitfalls of setting enable_nestloop to OFF) At the moment, what I do, is wrap the Report query in a database trasaction, and set the enable_nestloop only within that transaction, … -
Unable to send messages via React frontend and POST requests fail on Django REST API panel
I am building a chat application using React for the frontend and Django for the backend. I am facing the following two issues: Issue with sending messages in React: When I try to send a message through the React app, I receive a 400 Bad Request error. The API request is made to the backend using a POST request, but the response indicates that there was a problem. The error message doesn't provide much insight, and I cannot send the message. Issue with POST request in Django REST API panel: When I try to make a POST request from the Django REST framework interface (admin panel) to send a chat message, the request seems to go through successfully but redirects to a blank page (without an error). The data is not posted, and nothing changes on the frontend. However, when I use curl to send the same request, it works fine. Here’s a snippet of the relevant React code for sending messages: const handleSendMessage = async () => { if (message.trim() || file) { setSendingMessage(true); const formData = new FormData(); formData.append('receiver', selectedContact.id); formData.append('content', message); if (file) formData.append('file', file); try { const response = await fetch(`http://127.0.0.1:8000/api/chat/${userData?.current_basic_user?.username}/`, { method: 'POST', headers: { … -
Django Docker Setup: OperationalError - "FATAL: database 'guardian_grid' does not exist" with PostgreSQL After Running for a Few Days
I’m experiencing a recurring issue with my Django project configured to run with PostgreSQL in Docker. After a few days of smooth operation, the PostgreSQL database unexpectedly fails, and I receive the following error: django.db.utils.OperationalError: connection to server at "postgres" (172.18.0.2), port 5432 failed: FATAL: database "guardian_grid" does not exist I’ve shared my Docker Compose configuration below. The setup includes volumes for persistent data and backup storage for PostgreSQL. Despite this, the database sometimes "disappears," and I’m unsure why this is happening. I’m looking for insights into potential causes and solutions to ensure the database remains intact. volumes: guardian_grid_local_postgres_data: {} guardian_grid_local_postgres_data_backups: {} services: postgres: build: context: . dockerfile: ./compose/production/postgres/Dockerfile image: guardian_grid_local_postgres container_name: guardian_grid_local_postgres volumes: - guardian_grid_local_postgres_data:/var/lib/postgresql/data - guardian_grid_local_postgres_data_backups:/backups - /home/ehabsami/Desktop/guardian_grid/init.sql:/docker-entrypoint-initdb.d/init.sql env_file: - .envs/.local/.postgres ports: - "5432:5432" healthcheck: test: ["CMD-SHELL", "pg_isready -U postgres"] interval: 10s retries: 5 guardian_grid: build: context: . dockerfile: ./compose/production/django/Dockerfile # Ensure correct path for Django Dockerfile restart: always image: guardian_grid_local_django container_name: guardian_grid_local_django depends_on: postgres: condition: service_healthy redis: condition: service_started volumes: - .:/app:z command: /bin/sh -c "/run.sh" # Ensure run.sh exists ports: - "8000:8000" env_file: - .envs/.local/.django redis: image: "redis:alpine" ports: - "6379:6379" # Python and dependencies setup FROM docker.io/python:3.12.4-slim-bookworm AS python # Python build stage FROM python … -
Django model to relate with "container" of another model multiple objects
Sorry for weird topic naming but trying to find out the best way to create model relation with some kind of objects set. Lets say I have some models: class Furniture(models.Model): title = models.CharField() category = models.ForeignKey(Category) price = models.PositiveIntegerField() class Plumbing(models.Model): title = models.CharField() .... class Part(models.Model): title = models.CharField() code = models.CharField() I want to build relations of every Furniture / Plumbing instances with some set of Part instances (like fittings, screws, etc.). The first most obvious approach is to create ManyToMany field in Furniture and Plumbing models. But wondering if there is another approach to create some kind of "container" to have all the objects related together. As we know - there is no one-to-many field in Django and I don't want to keep planty null fields in Part if I decide to make relations for many other models (not only Furniture and Plumbing). I know that models archutecture is weid since it's a legacy code but any suggestions are welcome. -
Django - Unable to convert a list of dictionary to a table
I've a list of dictionary. mylist = [{'id': 1, 'name': 'abc'}, {'id': 2, 'name': 'xyz'}] i'm passing this mylist to an html page. return render(request, "viewdb.html", {'mylist':mylist}) and in my viewdb.html, code is as given below. {% if mylist %} <table> <tr> <th> ID </th> <th> Name </th> </tr> {% for user in mylist %} {% for key, value in user.items %} <tr> <td> {{ value }} </td> <td> {{ value }} </td> </tr> </table> {% endfor %} {% endfor %} {% endif %} </body>``` I want the table to look like this. ID NAME 1 abc 2 xyz please help. -
CustomUser model setup in django rest framework
i tried creating a CustomUser model which inherits from AbstractBaseUser in drf, but when i try creating a new super user to log into the admin site, it doesn't work. it shows superuser created successfully but when running manage.py shell and trying to get that exact user i just created, it apparently doesn't exist. my custom user model: from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, Group, Permission from .managers import UserManager from django.utils.translation import gettext_lazy as lz import uuid import base64 ITEM = ( ("pastries", 'pastries'), ("rentals",'rentals'), ("music", 'music'), ("help", 'help') ) class CustomUser(AbstractBaseUser, PermissionsMixin): objects = UserManager() id = models.CharField(max_length=12, unique=True, primary_key=True, editable=False) username = models.CharField(max_length=55, unique=True) email = models.EmailField(verbose_name=lz('email address'), unique=True, max_length=255) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) last_login = models.DateTimeField(null=True, blank=True) is_verified = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) groups = models.ManyToManyField( Group, related_name='accounts_user_groups', blank=True, help_text="the groups this user belongs to", verbose_name=lz('groups') ) user_permissions = models.ManyToManyField( Permission, related_name='accounts_user_permissions', blank=True, help_text="permissions for this user", verbose_name=lz('user permissions') ) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["username"] def __str__(self) -> str: return self.email @property def get_full_name(self): return f'{self.first_name} {self.last_name}' def save(self, *args, **kwargs): if not self.id: # Generate a shorter base64-encoded UUID hex_string … -
pyodbc Transactions in Django View are Committing Changes Despite Rollback Attempts
I'm working on a Django application where I'm using pyodbc to connect to an AWS RDS SQL Server database. I need to run a series of raw SQL queries (including INSERT, UPDATE, DELETE, DISABLE or ENABLE a trigger etc.) as a transaction, ensuring that no changes are committed if any error occurs during execution. However, I’m running into an issue where changes are getting committed to the database even when an error occurs, and I call rollback(). Here’s what I’ve tried so far: Set autocommit = False on the pyodbc connection to prevent automatic commits. Used multiple cursors for different SQL statements, all under the same connection with autocommit = False. Wrapped the Django view with @transaction.non_atomic_requests to disable Django’s default transaction handling. Also tried wrapping the code with transaction.atomic() to see if Django’s transaction management could help. Despite all of these efforts, changes are still being committed to the database after the error occurs in the Django view, but when I run the exact same code in a standalone Python script (outside of Django), the rollback works perfectly, and no changes are committed. Here’s a simplified version of the code I’m using: import pyodbc from django.conf import settings from … -
Issue with django-crispy-forms and django-filter: CSS class not applying to custom ChoiceFilter field
I'm using django-filter and django-crispy-forms to create a filter form in Django, but I'm having trouble applying a CSS class to a custom ChoiceFilter field. The CSS class is successfully applied to the date field but does not work for the transaction_type field, which is defined as a ChoiceFilter. Here’s my current code: import django_filters from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Field from .models import Transaction class TransactionFilter(django_filters.FilterSet): type = django_filters.ChoiceFilter( choices=Transaction.TRANSACTION_TYPE_CHOICES, field_name="type", lookup_expr="iexact", empty_label="Any", ) class Meta: model = Transaction fields = ['transaction_type', 'date'] def __init__(self, *args, **kwargs): super(TransactionFilter, self).__init__(*args, **kwargs) self.form.helper = FormHelper() self.form.helper.form_method = 'GET' self.form.helper.layout = Layout( Field('transaction_type', css_class='MY-CLASS'), Field('date', css_class='MY-CLASS'), ) In this setup, I expected both fields to have the MY-CLASS CSS class, but only the date field reflects it, not transaction_type. I suspect this might be due to transaction_type being a custom ChoiceFilter field, but I'm not sure how to resolve it. I've tried a few different approaches, such as updating widget attributes and applying CSS directly through attrs, but nothing has worked so far. Has anyone encountered this issue before or have suggestions on how to force the CSS class to apply to the ChoiceFilter field? -
'TranscriptionConsumer' object has no attribute 'base_send' Websocket Django
I'm trying to do site that translates .wav audio into text in django. I've got a problem here. I'm using websocket to send translated text immediately. But when I try to send a text, this error occurs ('TranscriptionConsumer' object has no attribute 'base_send') views.py # this function recognites text and send it to Consumers's function def get_large_audio_transcription(path,language, consumer ,minutes=2): sound = AudioSegment.from_file(path) chunk_length_ms = int(1000*60*minutes) chunks = [sound[i:i + chunk_length_ms] for i in range(0, len(sound), chunk_length_ms)] folder_name=str(settings.MEDIA_ROOT) + "/audio-chunks/" if not os.path.isdir(folder_name): os.mkdir(folder_name) whole_text = "" for i, audio_chunk in enumerate(chunks,start=1): chunk_filename = os.path.join(folder_name, f"chunk{i}.wav") audio_chunk.export(chunk_filename, format="wav") try: text = transcribe_small_audio(chunk_filename, language=language) except sr.UnknownValueError as e: print("Error:", str(e)) else: text = f"{text.capitalize()}." print(text) whole_text += text json_transcribe = json.dumps({"message": text}) # Sending json text through WebSocket consumer.send_json(json_transcribe) # deleting chunk try: os.remove(chunk_filename) except FileNotFoundError: print("Error: file not found") return whole_text @login_required(login_url='login_user') def index(request): context = None audio_form = UploadFileForm() if request.method == "POST": audio_form = UploadFileForm(request.POST, request.FILES) if not audio_form.is_valid(): messages.success(request, ("Error!")) return render(request, 'recognition/index.html', {"error": "Provide a valid file"}) try: form = audio_form.save(commit=False) form.name = request.user form.save() file = form.audio # get the audio file_size = file.size file_path = str(settings.MEDIA_ROOT) + '/' + str(file.name) consumer = TranscriptionConsumer() messages.success(request, ("File … -
Django compiling to pyc and running server
Ok so i run python -m compileall . However the generated files are in pycache manage.cpython-311.pyc and urls.cpython-311 my issue is when i run python manage.cpython-311.pyc runserver I keep getting the error File "<frozen importlib._bootstrap>", line 1204, in _gcd_import File "<frozen importlib._bootstrap>", line 1176, in _find_and_load File "<frozen importlib._bootstrap>", line 1126, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1204, in _gcd_import File "<frozen importlib._bootstrap>", line 1176, in _find_and_load File "<frozen importlib._bootstrap>", line 1140, in _find_and_load_unlocked ModuleNotFoundError: No module named 'settings' I am not the brightest django developer. However, i would appreciate if someone shares with me how to fix this issue. -
Shorcut for opening vs code from windows explorer
Is there any keyboard shortcut that i can use to open folder in vs code from windows explorer. I am too lazy to right click and open that with vs code. -
How to ManifestStaticFilesStorage with django-storages, boto3 on DigitalOcean Spaces Object Storage?
Context: I am running Django==5.1.2. I need to have cache busting for my static files on prod. On dev, my settings are like so STORAGES = { "default": { "BACKEND": "django.core.files.storage.FileSystemStorage", }, "staticfiles": { "BACKEND": "django.contrib.staticfiles.storage.ManifestStaticFilesStorage", }, } STATIC_URL = "static/" STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") This works as you would expect. When debug=False, django uses the hashed static files for the urls. But on prod my settings are like so # DigitalOcean Spaces Settings # Ref: https://www.digitalocean.com/community/tutorials/how-to-set-up-object-storage-with-django AWS_ACCESS_KEY_ID = os.getenv("DO_SOS_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY = os.getenv("DO_SOS_SECRET_ACCESS_KEY") AWS_STORAGE_BUCKET_NAME = os.getenv("DO_SOS_STORAGE_BUCKET_NAME") AWS_S3_ENDPOINT_URL = os.getenv("DO_SOS_ENDPOINT_URL") AWS_S3_OBJECT_PARAMETERS = { "CacheControl": "max-age=86400", } AWS_DEFAULT_ACL = "public-read" STORAGES["default"]["BACKEND"] = "storages.backends.s3boto3.S3Boto3Storage" STORAGES["staticfiles"]["BACKEND"] = "storages.backends.s3boto3.S3Boto3Storage" AWS_S3_SIGNATURE_VERSION = ( "s3v4" ) AWS_S3_CUSTOM_DOMAIN = os.getenv("DO_SOS_CUSTOM_DOMAIN") # Static & Media URL STATIC_URL = f"{AWS_S3_ENDPOINT_URL}/static/" MEDIA_URL = f"{AWS_S3_ENDPOINT_URL}/media/" As you can see, the backend is using "storages.backends.s3boto3.S3Boto3Storage" on prod instead of "django.contrib.staticfiles.storage.ManifestStaticFilesStorage". Which is kindof my problem. Whatever static content is saved to my Digital Ocean Spaces Object Storage is not hashed. How can I configure my django project to save the hashed static files to my Spaces Object Storage? -
Document is empty after performing fitz.open() on an io.BytesIO stream of a pdf
I am trying to get a PDF file from Mongodb and convert it to an io.BytesIO stream to keep it in the memory. Here is the snippet. fs = gridfs.GridFS(db) outputData = fs.get(file_id).read() pdf_stream = io.BytesIO(outputData) # Open the PDF from the stream doc = fitz.open(stream=pdf_stream, filetype="pdf") Running the Debugger I can see that the outputData is correct and has b'%PDF-' indicating a valid PDF. The pdf_stream is also generated correctly, but when I try to open this using fitz.open(), the document created is empty and returns Document('', <memory, doc# 2>) I am not able to figure out what the problem is and would like to have to help. -
Follow-up: How to override the Map Widget in Django Admin in which Geom Data Loaded via LayerMapping?
This question follows up on my initial query about dynamically changing the color of shapefile layers on a Django Admin Leaflet map. In my GeoDjango project, I'm loading geometry data via the LayerMapping method. Below is the load.py file I'm using for this: from django.contrib.gis.utils import LayerMapping from .models import Municipality municipality_mapping = { 'reg_code': 'Reg_Code', 'reg_name': 'Reg_Name', 'pro_name': 'Pro_Name', 'mun_code': 'Mun_Code', 'mun_name': 'Mun_Name', 'mean_ctrl': 'mean_ctrl', 'geom': 'MULTIPOLYGON', } zonalmeanctrl_shp = "path/to/shapefile.shp" def run(verbose=True): lm = LayerMapping(Municipality, zonalmeanctrl_shp, municipality_mapping, transform=False) lm.save(strict=True, verbose=verbose) In admin.py, I configured the admin panel with LeafletGeoAdmin: from django.contrib import admin from .models import Municipality from leaflet.admin import LeafletGeoAdmin class MunicipalityAdmin(LeafletGeoAdmin): list_display = ('pro_name', 'reg_code', 'reg_name', 'mun_code', 'mun_name', 'mean_ctrl') admin.site.register(Municipality, MunicipalityAdmin) Now, I would like to go further by customizing the map widget to dynamically style the geometries based on certain attributes (e.g., changing the color based on the mean_ctrl value). How can I override the map widget in Django Admin to apply dynamic colors to these shapefiles loaded via LayerMapping? -
django rest framework with simplejwt getting a 200 ok response even for invalid tokens
I am using django-rest-framework, djoser and simplejwt to build out token auth for user accounts. I can create an account, activate and login with Postman. But for some reason I having an issue with the /refresh and /verify endpoints. I'm also having an issue with /logout and /auth/me but I'm guessing if I can fix the /refresh and /verify endpoints the other ones will also fix themselves. These are the test urls and methods that I'm using with Postman POST http://localhost:8000/api/users/ After this I go to my email and copy the uid and token POST http://localhost:8000/api/users/activation/ enter the uid and token in the body of the request POST http://localhost:8000/api/jwt/create/ make sure email and pw are in the body and click send, receive refresh and access tokens POST http://localhost:8000/api/jwt/refresh/ enter the refresh token like so {"refresh": "kjlsjfdlskldjfls...."} It is here that I will enter an extra character at the end to make it and invalid token, but I still get a 200 ok along with an access token, why? POST http://localhost:8000/api/jwt/verify enter {"token": "jaslkfjsld...."} again, enter an extra character to invalidate the token but I still get a 200 ok with an access token, why? I have poured over what I … -
Django/Whitenoise collectstatic causing Permission Denied Error
I have been struggling with this for weeks and have hit a brick wall. Im trying to deploy a Django App and Im using Whitenoise to handle Static Data. When I run collectstatic I get “Permissions Denied” Error. How do I run collectstatic so that it can run without Permission problems. Django is installed in a virtualenv so running it as sudo doesn’t work. The error happens when using Whitenoise to handle static file using collectstatic when DEBUG is True or False and whether I use the Whitenoise STATICFILES_STORAGE or the Django version. $ python3 manage.py collectstatic “ File "/home/artillery/a1_lounge/web_dev/webdesign_biz/Portfolio/React/Vite/django/.venv/lib/python3.10/site-packages/django/core/files/storage/filesystem.py", line 106, in _save fd = os.open(full_path, self.OS_OPEN_FLAGS, 0o666) PermissionError: [Errno 13] Permission denied: '/home/artillery/a1_lounge/web_dev/webdesign_biz/Portfolio/React/Vite/django/hotdog/staticfiles/admin/js/admin/RelatedObjectLookups.js'” settings.py INSTALLED_APPS = [ 'hotdog_app', 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', # Whitenoise serves static in Dev and Prod 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', # Enable Whitenoise 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" Normally creating a file will give standard permissions eg (.venv) $ touch test.txt -rw-rw-r-- 1 artillery artillery 0 Nov 8 13:00 text.txt On first run of collectstatic (.venv) $ python3 manage.py collectstatic PermissionError: [Errno 13] Permission denied: … -
clear the shoping cart in django app that saving in session with clery task
hello i try to build a E commerce app with Django i have a shoping cart class that woek with session this is my cart class : from django.conf import settings from shop.models import Product, ProductColor from django.shortcuts import get_object_or_404 from django.utils import timezone class Cart: def __init__(self, request_or_session_data): if hasattr(request_or_session_data, 'session'): # Check if it's a request self.session = request_or_session_data.session else: # If it's session data, use it directly self.session = request_or_session_data cart = self.session.get(settings.CART_SESSION_ID) if not cart: cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart self.total_discount = None self.discount_code = None self.have_discount_code = self.session.get("have_discount_code", False) self.discount_code_amount = self.session.get("discount_code_amount", 0) self.last_updated = self.session.get("last_updated") if hasattr(request_or_session_data, 'user') and request_or_session_data.user.is_authenticated: self.user = request_or_session_data.user def add(self, product, color_id, quantity=1, override_quantity=False): product_id = str(product.id) color = get_object_or_404(ProductColor, id=color_id) cart_key = f"{product_id}_{color_id}" if cart_key not in self.cart: self.cart[cart_key] = { 'color_id': str(color.id), 'quantity': 0, 'price': str(product.price), 'discount': str(product.discount), 'discount_price': str(product.get_discounted_price()), } if override_quantity: self.cart[cart_key]['quantity'] = quantity else: self.cart[cart_key]['quantity'] += quantity self.total_discount = self.get_total_discount() self.save() def mark_session_modified(self): # Mark session as modified if `self.session` is a Django session object if hasattr(self.session, 'modified'): self.session.modified = True def save(self): # mark the session as "modified" to make sure it gets saved self.last_updated = timezone.now() self.session[settings.CART_SESSION_ID] = self.cart … -
Can't connect to Django Channels virtual server on Ubuntu
I want to deploy Django channels with gunicorn and nginx: this is my codes: gunicorn.service: [Unit] Description=Gunicorn instance to serve mysite After=network.target [Service] User=root Group=www-data WorkingDirectory=/root/mysite ExecStart=/root/apiKomarket/venv/bin/daphne -u /run/mysite.sock mysite.asgi:application -b 127.0.0.1 -p 8002 [Install] WantedBy=multi-user.target nginx: server { listen 80; server_name komarket.net; location / { proxy_pass http://unix:/run/mysite.sock; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } asgi.py: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter(websocket_urlpatterns)), }) router.py: websocket_urlpatterns = [ path("ws/order/", mycunsomer.as_asgi()), ] consumer.py: class mycunsomer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): pass def receive(self, text_data=None, bytes_data=None): pass home.html: const chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/order/' ); but this codes rais this error: Traceback (most recent call last): File "/root/apiKomarket/venv/lib/python3.10/site-packages/django/template/base.py", line 906, in _resolve_lookup raise VariableDoesNotExist( django.template.base.VariableDoesNotExist: Failed lookup for key [name] in <URLResolver <module 'API.urls' from '/root/apiKomarket/./API/urls.py'> (None:None) 'apis/'> Not Found: /favicon.ico -
How do I keep persistent web socket connections with another API in my Django app?
I'm developing a Django application that requires a persistent WebSocket connection to continuously fetch live data from a crypto market API. I need to keep this WebSocket connection active throughout the application's lifecycle to update my local data as new information arrives. This updated data will later be displayed on the front end, so I anticipate needing a separate WebSocket connection between the front end and back end (one connection for backend-to-crypto market API, and another for backend-to-frontend). I'm new to this type of setup and would appreciate guidance on the best practices for implementing it. I've explored Django Channels, Uvicorn, and Daphne. Although Django Channels might be suitable for the frontend-backend WebSocket connection, I'm more focused on maintaining a robust event-loop structure for the backend-to-crypto API connection to ensure it remains alive and responsive. I'm considering building a custom event-loop manager to handle this, but I'm unsure if it's the best approach. Could you suggest any established methods, libraries, or patterns for maintaining a continuous WebSocket connection for real-time data updates in a Django application? Thank you in advance! -
How to handle pre-selection of related fields and ensure proper update of many-to-many relationships in Django REST Framework?
I am working on implementing a Role-Based Access Control using Django and Django Rest Framework. I want to create a role with a set of permissions through the DRF browsable API. Additionally, I need the functionality to update those permissions, including adding new ones and removing existing ones. When displaying a role in the browsable API, I want the associated permissions to be pre-selected for clarity, while also showing all other available permissions for easy addition. What I have done so far Here is a simplified version of my model class BaseModel(models.Model): pkid = models.BigAutoField(primary_key=True, editable=False) id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=True) class Meta: abstract = True class Role(BaseModel): name = models.CharField(max_length=100) class Permission(BaseModel): name = models.CharField(max_length=100, unique=True) description = models.TextField(null=True, blank=True) class RolePermission(BaseModel): role = models.ForeignKey( Role, on_delete=models.CASCADE, related_name="role_permissions" ) permission = models.ForeignKey(Permission, on_delete=models.CASCADE) Here is my serializer class RoleSerializer(serializers.ModelSerializer): permissions = serializers.SlugRelatedField( queryset=Permission.objects.all(), many=True, required=False, slug_field="name" ) business = serializers.PrimaryKeyRelatedField( queryset=Business.objects.all(), required=False, allow_null=True ) class Meta: model = Role fields = ("id", "name", "is_default", "permissions", "business") def to_representation(self, instance): representation = super().to_representation(instance) permissions = instance.role_permissions.all().values_list( "permission__name", flat=True ) representation["permissions"] = list(permissions) return representation def to_internal_value(self, data): data = data.copy() permissions_data … -
Multi tenant structure where frontend is custom domain : Cookies set as thirdparty
For some context - using django on backend and nextjs on frontend. On frontend, there is option to connect custom domains. When backend saves a session cookie in the browser, it is set as a third-party cookie (even though it is for/from the same service) Now chrome does not allow third party cookies in incognito which breaks my flows in incognito window. Is there a way around this using the existing system? OR Will I have to implement this on my own? Thanks in advance -
How to create a dropdown in forms in django with values from database
I'm trying to create a form with a drop down box where the user can select the location from the pre-exsiting locations in table.Stuck on what to do forms.py from django import forms from .models import Vehicles from .models import HomeLocation class VehicleForm(forms.ModelForm): HomeLocation= forms.ModelChoiceField (queryset=HomeLocation.objects.all(), empty_label="Select a home location" # Optional ) class Meta: model = Vehicles feilds=['home_location','model','make','year'] exclude = ['Location lat', 'Location long'] model.py from django.db import models class HomeLocation(models.Model): home_location_id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) address = models.CharField(max_length=255) class Vehicles(models.Model): vehicle_id = models.AutoField(primary_key=True) home_location = models.ForeignKey(HomeLocation, models.DO_NOTHING) model = models.CharField(max_length=255) make = models.CharField(max_length=255) year = models.IntegerField() views.py from django.shortcuts import render from .models import Vehicles from .models import HomeLocation from .forms import VehicleForm from django.contrib import messages from django.http import HttpResponse # Create your views here. def addVehicle(request): if request.method =="POST": form = VehicleForm(request.POST or None) if form.is_valid(): form.save() messages.success(request,("Vehicle has been added successfully")) else: return render(request,'add_vehicle.html',{}) add_vehicle.html <form method="POST" action= "{% url 'addVehicle' %}"> {% csrf_token %} <div class="form-header"> <h1>Add Vehicle</h1> </div> <div class="form-group"> <div class="mb-3"> <select> {% for i in HomeLocation %} <option value="{{ i.home_location_id }}"> {{ i.name }} </option> {% endfor %} </select> </div></div> This is what I have done so far. But no … -
Django: the Celery signal, Redis Channel and AsyncWebsocket stack is not working
I'm trying to trigger a WebSocket function from my celery Signal using redis channels. So this is my AsyncWebsocket: class Consumer(AsyncWebsocketConsumer): async def connect(self): self.room_group_name = 'test' # Ensure consistent group name await self.channel_layer.group_add(self.room_group_name, self.channel_name) print(f"Consumer {self.channel_name} joined group {self.room_group_name}") # Debugging line await self.accept() def chat_message(self, event): message = event['message'] print(f"Chat message received: {message}") self.send(text_data=json.dumps({ 'type':'chat', 'message':message })) This is my Signal: async def send_chat_message(task_id, message): channel_layer = get_channel_layer() group_name = f"teste" # Send message to the WebSocket group await channel_layer.group_send( group_name, { 'type': 'chat_message', 'message': message } ) @task_success.connect def task_success_handler(sender, result, **kwargs): message = f"Task {task_id} has completed successfully!" async_to_sync(send_chat_message)(task_id, message) print(message) And this is my redis config: CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('redis', 6379)], }, }, } Note: I'm using docker, thats why host is "redis" and also I'm sure my django container can comunicate with the Redis container because when I use the Consumer, the redis monitor outputs: 1731094047.426342 [0 192.168.96.6:47094] "EVAL" "\n local backed_up = redis.call('ZRANGE', ARGV[2], 0, -1, 'WITHSCORES')\n for i = #backed_up, 1, -2 do\n redis.call('ZADD', ARGV[1], backed_up[i], backed_up[i - 1])\n end\n redis.call('DEL', ARGV[2])\n " "0" "asgispecific.d7702f4e3ed345e39497687e16c7ebd5!" "asgispecific.d7702f4e3ed345e39497687e16c7ebd5!$inflight" 1731094047.426476 [0 lua] "ZRANGE" "asgispecific.d7702f4e3ed345e39497687e16c7ebd5!$inflight" "0" "-1" "WITHSCORES" 1731094047.426485 …