Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
ModuleNotFoundError: No module named 'django_filters' in Python django framwork
when I run this command in vs code: python manage.py runserver I got the error: ModuleNotFoundError: No module named 'django_filters' I have already put 'django_filters' in installed app and the server is showing that Module is not found, what could be the instance solution to it if any stackoverflower is know to it please share your knowledge, Thank you in advance ! INSTALLED_APPS = [ .... 'django_filters', ] enter image description here -
Needs a Django developer for collaboration
I need someone that can help for my school management project and I need someone who can do a feature for it in my Django project Resolve it together and share budget after the project, so the person can contact davididohou33@gmail.com -
Flutter Mobile App with Firebase Auth[Google Sign In] + Django Rest Framework for backend
Please I am new to django[rest framework] for backend and I need help. I am working on a flutter mobile app and I'm using firebase as my authentication platform - is there a way in which I am already using flutter to develop the mobile app, firebase as the authentication just for signing users and then Django[Django rest framework] as the backend in such a way that signed in users on firebase can authenticate with Django [Django rest framework] to retrieve and modify data. I want to use django because I already have a foundation in python and I hate firebase rules -
having generic fields based on model objects in forms.py in django
We have a model called Permission and we have listed it in a form in django template like this: {% for item in permissions %} <tr> <td class="text-nowrap">{{ item.app }}</td> <td> <div class="d-flex"> <div class="form-check me-3 me-lg-5 mb-0 mt-0"> <input class="form-check-input" type="checkbox" name="{{ item.app }}_add" id="{{ item.app }}ManagementWrite"> <label class="form-check-label" for="{{ item.app }}ManagementWrite">add</label> </div> <div class="form-check me-3 me-lg-5 mb-0 mt-0"> <input class="form-check-input" type="checkbox" name="{{ item.app }}_read" id="{{ item.app }}ManagementRead"> <label class="form-check-label" for="{{ item.app }}ManagementRead">read</label> </div> <div class="form-check me-3 me-lg-5 mb-0 mt-0"> <input class="form-check-input" type="checkbox" name="{{ item.app }}_update" id="{{ item.app }}ManagementUpdate"> <label class="form-check-label" for="{{ item.app }}ManagementUpdate">update</label> </div> <div class="form-check mb-0 mt-0"> <input class="form-check-input" type="checkbox" name="{{ item.app }}_delete" id="{{ item.app }}ManagementDelete"> <label class="form-check-label" for="{{ item.app }}ManagementDelete">delete</label> </div> </div> </td> </tr> {% endfor %} So here We have four options for read , write , update and delete for each object in the Permission table . But How can i make a form in forms.py for this that i have BoleanFields for each access level? for example four field for ticket app (read , write , update , delete) and four field for users app as the same . -
How to pre-populate a form field with model's foreignkey field's value at form load in Django
I have the following models: class Member(models.Model): member_id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) class Photo(models.Model): photo_id = models.AutoField(primary_key=True) member_photo = models.ImageField(upload_to='member/', null=True, blank=True) member = models.ForeignKey(Member, on_delete=models.CASCADE) I have created model form, generic views for creating and updating the Member class. From here, I want to be able to upload members' photos to the second model 'Photo' directly from the ListView for "Member", by adding a link to the CreateView for uploading the photo. The ModelForm and CreateView for adding the photos are: ModelForm class MemberPhotoAddForm(forms.ModelForm): class Meta: model = Photo fields = ('member', 'member_photo') widgets = { 'member': forms.TextInput(attrs={'placeholder': 'Type name...', }), 'member_photo': forms.FileInput(attrs={'onchange': 'readURL(this)'}), } CreateView class PhotoUpload(CreateView): template_name = "member_photo_add.html" model = Photo form_class = MemberPhotoAddForm success_url = reverse_lazy('member_list') # URL for the ListView for Member class # I am trying to use method 'get_inital()' to pass 'member_id' to the form to add a 'Photo' def get_initial(self): member = self.request.GET.get('Member') return { 'member': member, } In urls.py, I have: ... path('member_acct/photos/add/<int:pk>', views.PhotoUpload.as_view(), name='member_photo_add'), ... In my template I am traversing thru' the fields in order to display the fields (and their values). However, as I am intending to do, I am unable to populate the member's primary …