Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Sending messages to all user's devices with django channels
I have been developing project. It uses django channels for websockets. And I meet a problem with sending ws messages to all device of the same account that is logged in. It is not a rare situation when many users use same accounts while project is under developing. So when one user is logged in and the other user is logged in and then he is logged out the first user does not receive messages. I tried to count devices but that method changes nothing. My consumer is: class NotificationConsumer(AsyncWebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(args, kwargs) self.user = None self.pool_name = None async def connect(self): self.user = self.scope["user"] self.pool_name = f"user_id_{self.scope['url_route']['kwargs']['user_id']}" await self.accept() # Join pool created = await self.add_online_user() if created: await self.channel_layer.group_add( self.pool_name, self.channel_name, ) async def disconnect(self, close_code): # Leave room group removed = await self.remove_online_user() if removed: await self.channel_layer.group_discard(self.pool_name, self.channel_name) # Receive message from WebSocket async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json["message"] # Send message to room group await self.channel_layer.group_send(self.pool_name, {"type": "read_message", "message": message}) # Receive message from room group async def notification_message(self, event): message = event["message"] await self.send(text_data=json.dumps({"message": [message]}, ensure_ascii=False)) @database_sync_to_async def add_online_user(self): online_user = OnlineUser.objects.filter(user=self.user).first() if not online_user: OnlineUser.objects.create(user=self.user, counter=1) return … -
Eager vs Lazy Loading: Best Data Fetching Strategies for Large-Scale Web Apps?
I'm building a large-scale web app with Django in Python (I might switch to Flask), and I'm trying to optimize how I fetch data. Specifically, I’m debating between eager loading (fetching all data upfront) and lazy loading (fetching data on-demand) for large datasets with complex relationships (e.g., nested data, foreign keys). My main challenges are over-fetching (retrieving too much data upfront), N+1 query problem (multiple unnecessary queries), user perceived latency (delays in loading data). What are the trade-offs between these approaches, and how can I decide when to use one over the other? Any tips on optimizing data fetching for performance while handling large volumes and real-time updates? TL;DR: How do you decide when to use eager vs lazy loading for large-scale apps with complex data and real-time updates? -
Django Object Storage doesn't reflect into my Object Storage
I'm attempting to integrate an Object Storage into my Django project, and my current setup includes Django, DRF, and PostgreSQL. Specifically, I'm attempting to handle an image upload from an API endpoint and store it in the Object Storage. class Announcement(models.Model): image = models.ImageField(upload_to='media/') Now when I try to access the API endpoint for the operation. The image is stored somewhere in my base_dir/media. and here's my boto3\storage setup AWS_ACCESS_KEY_ID = os.environ.get('DO_SPACES_KEY') AWS_SECRET_ACCESS_KEY = os.environ.get('DO_SPACES_SECRET') AWS_STORAGE_BUCKET_NAME = os.environ.get('DO_SPACES_BUCKET') AWS_S3_ENDPOINT_URL = os.environ.get('DO_SPACES_ENDPOINT') AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'media' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_ENDPOINT_URL, 'static') MEDIA_URL = 'https://%s/%s/' % (AWS_S3_ENDPOINT_URL, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' I tried reconfiguring the settings but had no success. I also checked the credentials, mediafiles, and runtime values of the data. I also checked the postgresql database, which contains what appears to be the image's URL in my object storage. -
File Management System but its not taking the data from form and cant submit
I have created a File Management System that allows users to create their own accounts, upload and manage files as well as create and manage albums. However, I want to create a limit of rows (of 10) for handling large data by adding pages to "Manage Files" and when creating an album as well in "Create Album" 'Picking Media Files'. I keep having errors as well when it comes to being able to submit the form, the checkboxes lose their checked state when submitting. I don't understand why Link to Code: Github -
Django IntegrityError: Unique Constraint Violation
I'm working on a Django project using Django Rest Framework (DRF) and PostgreSQL, with a Scan model that tracks different phases of a label scan. I've set a unique constraint on the combination of label_id and phase fields to prevent duplicate scans for the same label in the same phase. Here’s my Scan model: class Scan(models.Model): user = models.ForeignKey("accounts.User", on_delete=models.CASCADE) label = models.ForeignKey("labels.Label", on_delete=models.CASCADE) phase = models.IntegerField( choices=ScanPhaseChoice.choices, default=ScanPhaseChoice.unknown.value, ) distribution = models.ForeignKey("factories.Distribution", null=True, blank=True, on_delete=models.CASCADE) store = models.ForeignKey("factories.Store", null=True, blank=True, on_delete=models.CASCADE) created_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now=True) class Meta: unique_together = ["label", "phase"] When I try to create a new scan, I get this error: django.db.utils.IntegrityError: duplicate key value violates unique constraint "labels_scan_label_id_phase_81ec6788_uniq" DETAIL: Key (label_id, phase)=(413, 1) already exists. I’ve verified that the combination of label_id and phase already exists in the database, but I’m not sure why this error is raised when I've used full_clean() to validate data in the save() method. What I’ve Tried Ensuring the constraint is defined in both the database and the model’s Meta class. Adding validate_unique in the clean and save methods, but it didn’t prevent the error. Using full_clean() in the save method, expecting it to check for unique constraints. Questions … -
(failed)net::ERR_BLOCKED_BY_ORB and (canceled) error while using gcp as backend for django app
i have a django application to write articles and upload images i used to store my media files in local now i want to change it to GCS bucket while doing it after creating a gcloud.py and changing the media_url and default_file_storage all these options to use GCP bucket i am still facing an error while uploading of an image in the django logs i am getting 200 status but i cant see the images in my bucket when i check the inspect tabs network i found that at the status column there are 2 errors beside my image (failed)net::ERR_BLOCKED_BY_ORB and (canceled) I was trying to change my django applications media storage from local to GCP bucket -
send post but treated as GET?? rest-framework-bundle
I have api with django rest framework bundle My api is like this, only accepts POST. @api_view(["POST"]) @authentication_classes([]) @permission_classes([]) def myapi_v1_result(request): then I sent to this api with POST button However it gets , Method Not allowed why does this happen? INFO: 127.0.0.1:49305 - "POST /myapi/v1/result HTTP/1.1" 200 OK Method Not Allowed: /myapi/v1/result WARNING:django.request:Method Not Allowed: /myapi/v1/result -
Formatting F Strings in Python - Using For Loop in F String in Python
I am Working With Django Email Templates To Send PNR Details, Now I Wanted to Share PNR Details in Text Format. For This I Used Serializer to Send Data But Nested Passenger Details are not specific they are dynamic some pnr have 2 passengers while some have 6 passengers. Now, When I Serialize the Data i Get {'id': 8, 'pnr': pnr_number, 'train_number': '12916', 'train_name': 'ASHRAM EXPRESS', 'boarding_date': '2023-19-12T00:00:00+05:30', 'boarding_point': 'ADI', 'reserved_from': 'JP', 'reserved_to': 'JP', 'reserved_class': 'SL', 'fare': '350.00', 'remark': None, 'status': 1, 'modified': '2024-05-00T17:06:13.065600+05:30', 'train_status': '', 'charting_status': 'Chart Not Prepared', 'passengers_details': [{'id': 7, 'name': 'Passenger 1', 'booking_status': 'RLWL/76/GN', 'current_status': 'RLWL/62'}, {'id': 8, 'name': 'Passenger 2', 'booking_status': 'RLWL/77/GN', 'current_status': 'RLWL/63'}]} And I Wanted to Use Fstring to Format This Text Hi {username}, Exciting news! Your PNR details for your upcoming journey are ready. PNR Number: {pnr} Here's a quick summary of your booking: PNR Details: PNR Number: {pnr} Train Number: {train_number} Train Name: {train_name} Reservation Class: {reservation_class} Boarding Date: {boarding_date}} Reserved From: {reserved_from} Reserved To: {reserved_to}} Boarding From: {boarding_from} Passenger Details: Name: {passenger.name} Booking: {passenger.booking_status} Current: {passenger.current_status} Other Details: Fare: {fare} Remark: {remark} Status: {train_status} Charting: {charting_status} Have a safe and pleasant journey! Note: This uses scrapping of PNR status from … -
Filter by date yields empty queryset
Django version 4.2.x The user picks a date, and I am trying to compare that to entries in the TeacherAvailability model. The model: class TeacherAvailability(models.Model): teacher = models.ForeignKey(TeacherProfile, on_delete=models.CASCADE) student = models.ForeignKey( StudentProfile, on_delete=models.CASCADE, default=None, blank=True, null=True) timeslot_start = models.DateTimeField(auto_now_add=False) with the function: def get_dayagenda(self, selectedDate): year = int(selectedDate[:4]) month = int(selectedDate[5:7]) day = int(selectedDate[8:10]) And I have tried to return both of the following: TeacherAvailability.objects.filter(student_id=None).filter(timeslot_start__year=year, timeslot_start__month=month, timeslot_start__day=day).values_list('id', 'timeslot_start', 'student_id', 'teacher_id') and TeacherAvailability.objects.filter(student_id=None).filter(timeslot_start__date=datetime.date(year, month, day)) Both are yielding an empty queryset, however if I try just to filter by year I get some results. -
Unable handle the Csrf-Token for GET request in Django
In Django framework, When it was a POST request, if you modify the Cookie CSRF token, its throws the 403 error. But when it was a GET request, I tried to modify the Cookie CSRF-token, and it returned a 200 OK status code. I also want to validate the token for the GET request. I mentioned {% csrf_token %} in the Forms templates , but it could not handle this issue for GET request. I tried @csrf_protect in the view , it did not helpful. -
Wagtail(django) and Nginx Static files not being served
I am deploying a wagtail site with nginx on rocky linux however, I cannot get the static files to be served by nginx. My nginx site config is as follows: server { listen 80; server_name 10.4.0.189; root /home/wagtail/apps/my_site; charset UTF-8; error_log /home/wagtail/apps/my_site/nginx-error.log; location = /favicon.ico {access_log off; log_not_found off;} location static/ { root /home/wagtail/apps/my_site/; } location / { proxy_set_header Host $http_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; proxy_pass http://unix:/run/gunicorn.sock; } } I have tried multiple block location configurations including alias. I have checked read/write permissions to the directory where the application resides: drwxrwxr-x. 6 wagtail nginx 4096 Nov 7 08:27 . drwxrwxr-x. 4 wagtail nginx 4096 Nov 6 14:41 .. -rwxrwxr-x. 1 wagtail nginx 2029 Nov 6 14:41 Dockerfile -rwxrwxr-x. 1 wagtail nginx 376 Nov 6 14:41 .dockerignore drwxrwxr-x. 6 wagtail nginx 4096 Nov 6 14:44 home drwxrwxr-x. 6 wagtail nginx 4096 Nov 7 08:34 my_site -rwxrwxr-x. 1 wagtail nginx 256 Nov 6 14:41 manage.py -rwxrwxr-x. 1 wagtail nginx 56199 Nov 7 13:31 nginx-error.log -rwxrwxr-x. 1 wagtail nginx 35 Nov 6 14:41 requirements.txt drwxrwxr-x. 4 wagtail nginx 4096 Nov 6 14:44 search drwxrwxr-x. 11 wagtail nginx 4096 Nov 7 13:07 static wagtail : wagtail nginx Nginx is … -
Problem with user authentication in django
For a reason unknown to me, when authenticating a user, I enter the following data: email and password, as a result, super users are authenticated, but ordinary users are not. What can be done about this? Has anyone encountered such a problem? Please help me solve this, I'm completely new to Django. Here are the files in the project (if you need any other files, write): views.py from django.contrib.auth import authenticate, login from django.http import HttpResponse from django.shortcuts import render, redirect from users.models import User def register(request): if request.method == "POST": username = request.POST.get("username") email = request.POST.get("email") password = request.POST.get("password") # password2 = request.POST.get("password2") phone_number = request.POST.get("phone_number") user = User ( username = username, email = email, password = password, phone_number = phone_number ) user.save() return redirect('main:index') return render(request, 'users/register.html') def user_login(request): if request.method == "POST": email = request.POST.get("email") password = request.POST.get("password") user = authenticate(email=email, password=password) if user and user.is_active: login(request, user) return HttpResponse('Authenticate!') else: return HttpResponse('No Login!') return render(request, 'users/login.html') models.py from django.db import models from phonenumber_field.modelfields import PhoneNumberField from django.contrib.auth.models import AbstractUser from users.managers import CustomUserManager class User (AbstractUser): username = models.CharField(max_length=20, unique=True) email = models.EmailField(unique=True) password = models.CharField(null=True, blank=False, max_length=30) phone_number = PhoneNumberField(region="IN", unique=True, null=True, blank=False) USERNAME_FIELD …