Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Does pyinstaller compile Django project/app very well?
It's quiet lengthy but here is it. The issue is I'm trying to build a school management system as a desktop software/application that runs offline using Django and Waitress to serve it. So, I built the server side GUI using Tkinter as the GUI and used waitress to serve the application wsgi. The code runs well when I run it directly from the terminal while I've activated the virtual environment but the moment I compile it to an executable/application using pyinstaller the server never connects. Gunicorn won't work because it's specific for Unix so, I opted for Waitress. I have configure my spec file to even import requirements from the virtual environment and requirements.txt to make sure every module and requirements are imported. I've really tried so much techniques but it won't just work but that's only after I've converted it to Executable using pyinstaller. I have configured my spec file to import from both my requirements.txt and virtual environment. -
Dependency Error in Railway even though the dependency is actually not listed
enter image description here I'm getting this error even though there is no "zee5" dependency in my django app. I checked this through How should I fix this issue? pip list I checked the installed packages in my environment to ensure that zee5 is not inadvertently installed. -
Getting 401 Unauthorized Error on Login in React Web App
Whenever I click the login button of my web page built with vite-react(frontend:5173), express(server 5000, to handle cookies httpOnly) and Django(backend:8080). the console logs an error of (GET http://localhost:5000/api/users/me 401 (Unauthorized)). Django terminal using VS Code also logs the same error. I've narrowed down the problem that it's between the React and express server. I'm also using redux-toolkit for the project and here is a part of the reducer I'm using to handle getting the user const getUser = createAsyncThunk( 'users/me', async (\_, thunkAPI) =\> { try{ //const accessToken = thunkAPI.getState().auth.accessToken; const res = await fetch(`${import.meta.env.VITE_API_URL}/api/users/me`, { method: 'GET', headers: { Accept: 'application/json', //Authorization: `Bearer ${accessToken}`, } }) const data = await res.json(); if(res.status === 200){ return data; } else { return thunkAPI.rejectWithValue(data); } } catch(err){ return thunkAPI.rejectWithValue(err.response.data); } } ) the VITE_API_URL in my environ is pointed at localhost:5000. The whole error disappears if I uncomment out the accessToken and header Authorization but I feel like I shouldn't need that when I'm using httpOnly and not local storage for tokens and I'm handling the cookie already in my 'me express router'. Here's my 'me router' for express import express from 'express'; import fetch from 'node-fetch'; const router = express.Router(); … -
Error 404 redirect not working in Django and static files not showing in edge
I am developing a single page webapp where I am trying to configure the error page if page not found so I have added proper settings but still my redirect not working on error page. Here is my settings.py from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-0t^!2rh2#u8fx1k(@+#oik8l$5i^xxxxxxxxxxxxxx' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['127.0.0.1', 'localhost'] # Add your domain here STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ArchanaComputersHome', 'django_dump_die', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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', 'django_dump_die.middleware.DumpAndDieMiddleware', ] ROOT_URLCONF = 'ArchanaComputers.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media' ], }, }, ] WSGI_APPLICATION = 'ArchanaComputers.wsgi.application' # Database # https://docs.djangoproject.com/en/5.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # … -
Djoser permissions
How do I set up djoser permissions so that it doesn't try to provide data for anonymous users? I try set up Djoser like this: DJOSER = { "LOGIN_FIELD": "email", "HIDE_USERS": False, "TOKEN_MODEL": "rest_framework.authtoken.models.Token", "SERIALIZERS": { "user": "users.serializers.UserSerializer", "current_user": "users.serializers.UserSerializer", "user_create": "users.serializers.UserCreateSerializer", }, "PERMISSIONS": { "user": ["rest_framework.permissions.IsAuthenticatedOrReadOnly"], "current_user": ["djoser.permissions.CurrentUserOrAdmin"], "user_list": ["rest_framework.permissions.IsAuthenticatedOrReadOnly"], },} but it doesn't work -
object has no attribute 'base_send' ( How can I call the function from AsyncWebsocketConsumer)
I have this script which receive the message and send the same message to the all connected browser. comsumer.py import json from channels.db import database_sync_to_async from channels.generic.websocket import AsyncWebsocketConsumer from .models import Message class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_group_name = 'chat' await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def push(self,message): print("pushing message") await self.send(text_data=json.dumps({ 'message': message })) async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] res = await self.save_message_to_db(message) await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': res['message_data'], } ) async def chat_message(self, event): message = event['message'] # WebSocketを介してメッセージを送信 await self.send(text_data=json.dumps({ 'message': message })) @database_sync_to_async def save_message_to_db(self, message_text): message = Message.objects.create(content=message_text) return { 'message_data': { 'id': message.id, 'content': message.content, 'timestamp': message.timestamp.isoformat(), } } And, this class is used as from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/chat/', consumers.ChatConsumer.as_asgi()), ] Now, I want to call async def push() from view or command script. For now, I am testing in management/commands/test_cmd.py from chat.consumers import ChatConsumer . . . chatConsumer = ChatConsumer() asyncio.run(chatConsumer.push("testtest")) This shows the error like this below. I guess I should init ChatConsumer(AsyncWebsocketConsumer) in a defferent way, How can I fix this?? Traceback (most recent … -
Django Website not accessible on some browsers
I have a web app built with django that is hosted online on a subdomain. It was working fine until a few days ago when certain users started getting errors trying to access it where it would say something like safari couldn't open the page because the server unexpectedly dropped the connection. As mentioned earlier it still works fine for some users, there is nothing of note in the server logs, any help would be great! I have tried re-deploying the site as well as clearing browser website data but to no avail -
Understanding sync_to_async method in Django?
I have never worked with asyncio and/or asynchronous methods with django and am having a little difficulty understanding. I am trying to convert a synchronous helper function (create_email_record) into an asynchronous function inside of a form method. I will minimize some code for better understanding. my form method (begin_processing) has a good amount of logic inside. def create_email_record(submission): print("-----CREATE EMAIL RECORD-------") creation = EmailRecord.objects.create() class Form(forms.Form): comments = forms.TextArea() def begin_processing(): submission = Submission.objects.get(id=1) print("----------BEGIN ASYNC--------") create_email_notification = sync_to_async(create_email_record)(submission) asyncio.run(create_email_notification) print("----------END ASYNC----------") When I print this to my console I would think to expect: ("----------BEGIN ASYNC--------") ("----------END ASYNC----------") ("-----CREATE EMAIL RECORD-------") What I receive is: ("----------BEGIN ASYNC--------") ("-----CREATE EMAIL RECORD-------") ("----------END ASYNC----------") My Object gets created, and seems to work, but I don't believe that my converted sync_to_async function is being converted/called correctly. Maybe I am having some trouble understanding, but what I want to do is call an asynchronous function from a synchronous function/method. I have read a lot on other posts, and online resources, but none seem to fit what I am looking to do. I have not seen this done inside of a form method. -
Django - select onchange event not working anymore if using jquery-editable-select
I'm using a select item from a django model with a onchange event to trig a JS script : forms.py class forms_bdc(forms.ModelForm): [...] bdc_description_1 = forms.ModelChoiceField(queryset=models_products.objects.values_list('product_denomination', flat=True),required=False, widget=forms.Select(attrs={'id': 'editable-select-2','onchange': 'populate_selected_product(this.id,this.value)'}),empty_label=None ) It works very well but if I'm using jquery-editable-select to transform my select item in sort of a searchable datalist, the onchange event does not trig the JS script anymore ... Anybody knows a workaround for this ? template.html <script> function populate_selected_product(product_selectbox_id, product_selectbox_value){ $.ajaxSetup({ data: { product_num: product_selectbox_value, csrfmiddlewaretoken: '{{ csrf_token }}' }, }); $.ajax({ type: "GET", url: "../populate_selected_product/", success: function (data) { $("#div_update_row_bdc_product").html(data) $('#'+product_selectbox_id).parent().find('#id_id_bdc').val($("#id_product_denomination").val()) } }); } // and here is the code to transform the select item with jquery-editable-select $('#editable-select-2').editableSelect({effects: 'fade'}); </script> -
Python Django Web App Returning 404 Error for the GET request
I have created a basic web app using Python Django. Currently only one API is implemented i.e. User/GetUserName.aspx which return as simple "Hello" message. The web service is running on Django's inbuilt dev server. The API get hit successfully from web browser with URL 127.0.0.1:8001/User/GetUserName.aspx or 192.168.10.120:8001/User/GetUserName.aspx and from PostMan as well. Now there is one legacy device on the same network which hits this API. I have configured it with my machine IP & web service port. When that device hits the API, it get 404 error. I performed analysis of the issue and have following observations: When I hit the API from browser or PostMan, then Django prints API on console as GET User/GetUserName.aspx 200. When the device hits the API, then Django prints API on console as GET https://192.168.10.120:8001/User/GetUserName.aspx. I also implemented same API in Python Flask where it runs smoothly. On reading the documents of the device, I found that device always make https connection with the server. However, for few APIs it set some flag "verify=false" which disables certificate verification. For other APIs, it performs certificate verification. I tried setting up https server with self signed certificate but in that case my web app don't … -
I need help changing my veterinary website to a hardware sales website
I need help changing my veterinary website to a hardware sales website What I expected when I changed it was that it would work in the same way as the veterinary one, but it falls off and I don't know how to make it work. please help -
Django hosted on Render - Media Files/template vars
I've got a Django app that stores its static and media files in an AWS S3 bucket. Retrieval, usage and storage of these files work fine locally. The issue is, when accessing through the live site hosted on Render, if I try to upload and display an image the web app errors and times out. I don't usually host my projects, so this might be something totally silly. I'd assumed that since the files are stored in S3, it would still be accessible the same? Perhaps I need to make some adjustments in Render? In Render logs, I've gotten some errors where it doesn't like/can't find values in the template variables I am using to display media images. These errors don't occur locally, so I'm a bit confused. It's a super long traceback, so I've tried to snippet the important/repeating bits. I'm not sure if this is to do with Render, my S3 bucket u;loads or Django template :( See the images/videos below: live issue video: https://drive.google.com/file/d/1yriXvreGSWv_FiRKOwxKEg-5TDzfyejU/view?usp=sharing working locally video: https://drive.google.com/file/d/1UA-_kUaE6f1HPjqrUkqNIR1gSXmBNHz3/view?usp=sharing You can find my code here for further inspection: https://github.com/KianaR/Colour-Picker Any ideas? -
Unable to enter json in django admin
In my model I have the following field - data_fields = ArrayField(models.JSONField(null=True, blank=True), blank=True, null=True) In order to test this out, I entered the following in the data_field in the django admin - [{"key": "name", "label": "Name"}, {"key": "amount", "label": "Amount"}] But I get an error saying Item 1 in the array did not validate: Enter a valid JSON. Item 2 in the array did not validate: Enter a valid JSON. Item 3 in the array did not validate: Enter a valid JSON. Item 4 in the array did not validate: Enter a valid JSON. I only get this error if there are multiple key-value pairs in the JSON. If there is only one JSON element with one key-value pair, it works. If there are multiple elements in the array, or there are multiple key-value pairs in the JSON field, I get the error above. Why is this happening, and how do I fix it? -
Managing Inconsistent Model Attribute State on WebSocket Reconnect (Django Channels)
import json, jwt, uuid, random from channels.generic.websocket import AsyncWebsocketConsumer from django.conf import settings from asgiref.sync import sync_to_async from .models import GameRoom class BattleshipConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_group_name = self.scope['url_route']['kwargs']['room_id'] token = self.scope['url_route']['kwargs']['token'] try: payload = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256']) self.username = payload['username'] self.guest_id = payload['guest_id'] await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() # Fetch the current state of the room self.room = await sync_to_async(GameRoom.objects.get)(room_name=self.room_group_name) initial_lobby_phase = self.room.lobby_phase # Log current state before making changes print(f"Initial room state for {self.username}: {initial_lobby_phase}") # Check if player1 or player2 is None and assign self.guest_id accordingly if self.room.player1 is None and self.room.player2 != self.guest_id: self.room.player1 = self.guest_id print(f'{self.username} has been added as player1') await sync_to_async(self.room.save)() elif self.room.player2 is None and self.room.player1 != self.guest_id: self.room.player2 = self.guest_id self.room.lobby_phase = 'setup' # Save the updated room and fetch it again to ensure consistency await sync_to_async(self.room.save)() print(f'{self.username} has been added as player2') self.room = await sync_to_async(GameRoom.objects.get)(room_name=self.room_group_name) #this works correctly, the lobby phase sent here is 'setup',as expected print("broadcasting phase change to setup") await self.channel_layer.group_send( self.room_group_name, { 'type': 'phase_change', 'phase': self.room.lobby_phase } ) # Fetch the latest state from the database after making changes self.room = await sync_to_async(GameRoom.objects.get)(room_name=self.room_group_name) lobby_phase = self.room.lobby_phase # Log updated state after changes print(f"Current room … -
Django sessionid cookies disappearing upon refresh
I am using a Django DRF backend with SessionAuthentication and a NextJS frontend. They are hosted on different ports. I am trying to use the django login function to automatically log the user in when creating an account. When I run this, the sessionid and csrf cookie gets saved into cookies but upon refresh they disappear. Before refresh: cookies in dev tools After refresh: cookies gone after refresh Relevant settings.py settings: CORS_ALLOW_CREDENTIALS = True CSRF_USE_SESSIONS = True SESSION_COOKIE_SECURE = True SESSION_COOKIE_SAMESITE = 'None' CORS_ALLOWED_ORIGINS = [ "https://localhost:3000", ] CSRF_TRUSTED_ORIGINS = { "https://localhost:3000" } View used: class UserView(APIView): renderer_classes = [JSONRenderer] permission_classes = [ permissions.AllowAny ] decorators = [sensitive_variables('password'), ensure_csrf_cookie] @method_decorator(decorators) def post(self, request, format=None): """Create User""" serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() username = serializer.validated_data['username'] password = serializer.validated_data['password'] user = authenticate(username=username, password=password) if user: login(request, user) return Response(data={'response': 'Successfully created account'}, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Request: const response = await fetch(`https://127.0.0.1:8000/user/`, { method: 'POST', mode: 'cors', credentials: 'include', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(data) }); Both django server and NextJS are running on a dev SSL certificate so both have https. -
Error While Running dajngo project server through WSL
I am using Postgres as my db for this project. My project directory is in my windows system. Virtual environment was created in both windows and wsl (ubuntu) with all the dependencies. Postgres-16 and pgadmmin4 are installed in my windows. I was try to run the server from WSL2 (ubuntu) using python3 manage.py runserver. Getting error in Exception in thread django-main-thread:. connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? port - 5432 is used by postgres for connection and i was unable to connect to postgres in my windows from WSL. PSQL is installed in my WSL psql --version psql (PostgreSQL) 14.12 (Ubuntu 14.12-0ubuntu0.22.04.1) I tried to add the subnets in my pg_hba.conf # IPv4 local connections: host all all 172.18.64.0/20 scram-sha-256 host all all 127.0.0.1/32 scram-sha-256 host all all 0.0.0.0/0 scram-sha-256 Double checked the listen_addresses = '*' in postgresql.conf I tried to connect the WSL with postgers but get an error psql -h 'localhost' -U postgres -d encryptdata2 psql: error: connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? -
403 error in django and enginx static files
I run the Django app with gunicorn and nginx on a virtual server. But it gives a 403 error for loading static files this is nginx config: enter image description here this is nginx sites-evailabel: enter image description here this is django project settings.py: enter image description here When I open the site, it gives this error in the browser console: enter image description here how can i fix this error? -
InvalidCursorName in django project
This is my models.py file: class TaskDetails(models.Model): TASK_CHOICES = [ ('ploughing', 'Ploughing'), ('sowing', 'Sowing'), ('watering', 'Watering'), ('harvesting', 'Harvesting'), ] task = models.CharField(max_length=50, choices=TASK_CHOICES) start_date = models.DateField() end_date = models.DateField() task_assigned_to = models.ForeignKey(WorkerDetails, on_delete=models.CASCADE) equipment_required = models.ManyToManyField(EquipmentDetails, related_name='tasks') def __str__(self): return self.task def clean(self): # Ensure all required equipment is available for equipment in self.equipment_required.all(): if equipment.status != 'available': raise ValidationError(f'Equipment {equipment.equipment} is not available.') def save(self, *args, **kwargs): self.clean() # Ensure clean method is called before saving super().save(*args, **kwargs) I am getting the following error: cursor "_django_curs_20672_sync_2" does not exist And i am using postgresql for database How to resolve this error? -
how to autogenerate context for APIView methods
I need to write my own APIView class which overrides drf's APIView and it will have autogenerated self.context which I can pass into serializer. For example class SomeView(APIView): def post(self, request): ser = SomeSerializer(data=request.data, context = self.context) ser.is_valid(raise_exception=True) return Response(ser.validated_data) -
Python Django : ssl.SSLEOFError: EOF occurred in violation of protocol (_ssl.c:2427)
Traceback (most recent call last): File "C:\Program Files\Python311\Lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Users\ADMİN\AppData\Roaming\Python\Python311\site-packages\django\core\servers\basehttp.py", line 173, in finish_response super().finish_response() File "C:\Program Files\Python311\Lib\wsgiref\handlers.py", line 184, in finish_response self.write(data) File "C:\Program Files\Python311\Lib\wsgiref\handlers.py", line 292, in write self._write(data) File "C:\Program Files\Python311\Lib\wsgiref\handlers.py", line 466, in _write result = self.stdout.write(data) ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\socketserver.py", line 834, in write self._sock.sendall(b) File "C:\Program Files\Python311\Lib\ssl.py", line 1274, in sendall v = self.send(byte_view[count:]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\ssl.py", line 1243, in send return self._sslobj.write(data) ^^^^^^^^^^^^^^^^^^^^^^^^ ssl.SSLEOFError: EOF occurred in violation of protocol (_ssl.c:2427) Hello Friends The problem I have is that the SSL Error error in the python layer is caught and processed in the Django layer. Here is the issue: We are developing a project in Python Django environment. We are using openssl for runsslserver architecture. We have designed an advanced logging architecture for this situation. However, despite prioritizing middelware first, we could not catch and log this ssl error. Thank you in advance to anyone who has ideas or suggestions on this issue. class SSLErrorMiddleware(MiddlewareMixin): def __init__(self, get_response): self.get_response = get_response # İstek başladığında ve bittiğinde sinyalleri bağla request_started.connect(self.log_request_start) request_finished.connect(self.log_request_finish) def __call__(self, request): # Request processing try: response = self.get_response(request) except ssl.SSLEOFError as e: error_details = traceback.format_exc() … -
Reverse for 'post_detail' with arguments ... not found
i'm having NoReverseMatch error message. already spend hours everything looks ok to me but couldn't figure it out. I would appreciate any help. thanks views.py from django.http import Http404 from django.shortcuts import get_object_or_404, render from blog.models import Post # Create your views here. def postList(request): posts = Post.objects.all() return render(request, 'blog/post/list.html',{'posts':posts}) def post_detail(request,year,month,day, post): post = get_object_or_404(Post, status = Post.Status.DRAFT, slug = post, publish__year=year, publish__month=month, publish__day=day) return render(request, 'blog/post/detail.html', {'post':post} ) urls.py from django.urls import path from . import views app_name = "blog" urlpatterns = [ path('', views.postList, name="post_list"), path('<int:year>/<int:month>/<int:day>/<slug:post>/', views.post_detail, name="post_detail"), ] models.py from django.urls import reverse from django.utils import timezone from django.db import models from django.contrib.auth.models import User # Create your models here. class Post(models.Model): class Status(models.TextChoices): DRAFT = 'DR', 'Draft' PUBLISHED = 'PB','Published' user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="blog_posts") title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') body = models.TextField() created = models.DateTimeField(auto_now_add=True) publish = models.DateTimeField(default=timezone.now) status = models.CharField(max_length= 2, choices=Status.choices, default=Status.DRAFT) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ['-publish'] indexes = [ models.Index(fields=['-publish']), ] def __str__(self): return self.title def get_absolute_url(self): return reverse("blog:post_detail", args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) list.html {% extends "blog/base.html" %} {% block content %} {% for post in posts %} <a href="{{ post.get_absolute_url }}">{{post.title}}</a> <p>{{post.body|truncatewords:30|linebreaks}} <p>{{post.created}}</p> {% … -
the filtered product can't be added to cart in django
I am working on a Django-based web application that includes a product filtering feature. Products are filtered based on various criteria such as category, vendor, and price range. The filtered products are correctly displayed on a page. However, I am facing an issue where the filtered products cannot be added to the shopping cart, while the unfiltered products can be added without any problems. I am a beginner in Django development, and I have tried troubleshooting this issue but have not been successful. I suspect there may be an issue with the way the filtered products are handled or how the add-to-cart functionality is implemented for these products. Any help or guidance from experienced developers to resolve this problem would be greatly appreciated. Thank you in advance! This is the filtered product list html which I have replicated from the product-list.html async/product-list.html {% for p in products %} <div class="col-lg-3 col-md-4 col-sm-6 mix oranges fresh-meat"> <div class="featured__item"> <div class="featured__item__pic set-bg" style="cursor: pointer; background-image: url('{{ p.image.url }}');" onclick="redirectToProductDetail('{{ p.pid }}')"> {% if p.get_percentage %} <div class="discount-badge"> {{ p.get_percentage | floatformat:0 }}% </div> {% endif %} <ul class="featured__item__pic__hover"> <li><a href="#" class="no-redirect"><i class="fa fa-heart"></i></a></li> <li><a href="#" class="no-redirect"><i class="fa fa-retweet"></i></a></li> <li> <div class="add-cart"> <input … -
Django form.cleaned_data switches values between Form class choice fields
I am trying to filter a model's objects dynamically depending on what the user selects in a form. The form allows selecting from two dropdown lists. Selecting from either dropdown is optional. If the user does not select anything and clicks Submit, there will be an empty search results page. I believe I didn't do some things correctly. When I extract data from form.cleaned_data, when field_1 is only selected by the user, its value is assigned to field_2 and field_1 ends up being assigned the string "field_1". Same for when only field_2 is selected. Why is it switching the value assignment and assigning the string name of each to itself? Output self.kwargs = {"field_1": "field_1", "field_2": field_1_value} self.kwargs = {"field_1": field_2_value, "field_2": "field_2"} However, when the user selects a value from each dropdown list, the values are properly assigned. Here is my code: views.py class MyDataView(generic.ListView): template_name = "my_data/my_data.html" context_object_name = "my_data_list" def get_context_data(self, **kwargs): context = super(MyDataView, self).get_context_data(**kwargs) context["form"] = SearchForm return context def get_queryset(self): # Update and create data in the MyData model populate_my_data() return MyData.objects.all() class MyDataSearcher(FormView): form_class = SearchForm def form_valid(self, form): field_1 = form.cleaned_data.get("field_1 ", "") field_2 = form.cleaned_data.get("field_2 ", "") kwargs = {} if … -
I want to configure my django admin as subdomain on nginx
I've configured Nginx to proxy requests for admin.myproject.com to my Django application running on port 8000. However, when accessing admin.myproject.com, it redirects to admin.myproject.com/admin and displays a "502 Bad Gateway" error. Here's my Nginx configuration for admin.myproject.com: `server { listen 80; server_name admin.myproject.com; location / { proxy_pass http://127.0.0.1:8000/admin/; 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; proxy_redirect off; } }` I expect requests to admin.myproject.com to be proxied to http://127.0.0.1:8000/admin without displaying /admin in the browser. However, it currently adds /admin to the URL and results in a "502 Bad Gateway" error. The Django application is correctly configured to handle requests to /admin. -
django DATETIME_INPUT_FORMATS not working after upgrading to django 5.0
I just upgraded to django 5.0, and the DATETIME_INPUT_FORMATS is no longer working in the settings.py file. It is not accepting DOY (%j) dates like it did before. I have looked at similar questions on stackoverflow, and I see that USE_L10N is deprecated and USE_L18N should be disabled. Even with these updates, it seems to be ignoring the DATETIME_INPUT_FORMATS. Ideas? ''' LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' DATETIME_FORMAT = 'Y-z H:i:s' USE_I18N = False USE_TZ = False DATETIME_INPUT_FORMATS = [ '%Y-%m-%d %H:%M:%S.%f', '%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M', '%Y-%m-%dT%H:%M:%S.%f', '%Y-%m-%dT%H:%M:%S', '%Y-%m-%dT%H:%M', '%Y-%m-%d', '%Y-%j %H:%M:%S.%f', '%Y-%j %H:%M:%S', '%Y-%j %H:%M', '%Y-%jT%H:%M:%S.%f', '%Y-%jT%H:%M:%S', '%Y-%jT%H:%M', ] '''