Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Stripe payment not going through in production but working in development
I have a django project that I am deploying and have a stripe integration for payments in it. It works perfectly fine locally and goes through but does not work on my linux server. What could be causing this and how can I make the payment work on my deployed version? Lead: The only hit of issue I am getting is that my gunicorn logs show that the /charge/ endpoint that I am using to charge is forbidden, but I'm not sure what is really causing this as this is so bizarre. Thank you so much! Context: I have https, and the code doesnt detect any errors (redirects to success page and stripe doesnt give errors). I just allowed all of the stripe IP's through my firewalls using sudo ufw (the api.stripe.com ones: https://docs.stripe.com/ips). The code is the exact same, the api keys are the same -
Django ModuleNotFoundError in Vercel production
I'm trying to deploy an api on vercel in Django, however when I call my api I get an error that a module does not exist. I don't get this error locally. I've tried several solutions: adding a route to the folder in settings.py, installing modules with build_files.sh. I still have the same problem, even though the files are present in the aborescense of my production project. Here is the link to my github repository: https://github.com/SkyBLUE62/osint_sherlock_api vercel.json { "version": 2, "builds": [ { "src": "api/wsgi.py", "use": "@vercel/python", "config": { "maxLambdaSize": "15mb", "runtime": "python3.9" } } ], "routes": [ { "src": "/static/(.*)", "dest": "/static/$1" }, { "src": "/(.*)", "dest": "api/wsgi.py" } ] } build_files.sh echo "BUILD START" # create a virtual environment named 'venv' if it doesn't already exist python3.9 -m venv venv # activate the virtual environment source venv/bin/activate # install all deps in the venv pip install -r requirements.txt # collect static files using the Python interpreter from venv python manage.py collectstatic --noinput python manage.py makemigrations python manage.py migrate python manage.py runserver echo "BUILD END" # [optional] Start the application here # python manage.py runserver api/settings.py """ Django settings for api project. Generated by 'django-admin startproject' using Django 3.1.4. … -
Half space in django CKEditor
I am developing a website that requires an advanced text editor for Persian, and I have used CKEditor. When I copy text from Microsoft Word and paste it into CKEditor, it does not paste all the half spaces correctly. For example, if the text of an article has 10 half spaces or somebody may call it semi space, after pasting it into the CKEditor, it might only display 7 half spaces correctly, and the rest are missing. Have you encountered a similar issue? What is your opinion? -
Django reversed for loop slice
I am currently trying to reverse a slice of a list going from 0 to 11 Here is part of index.html <div> {% for i in game.board|slice:"6:12" reversed%} <a href="{% url 'make_move' forloop.counter0 %}" > {{ i }} </a> {% endfor %} </div> Here is what I have in views.py def make_move(request, pit): print(f"Make move called. Pit: {pit}") pit will always print from 0 to 5, when I expect it to print 11, 10, 9, etc It feels that slice and reversed have no effect on i in this case -
How to use <img src ""> in django
I am making a website using django and flowbite tailwind component library i want to add a carousel to my website ` ` in normal websites we use something like <img src="./img.jpg> This is what i had already tried its a response from chatgpt its not working To access an image stored at webdept/home/media/image.jpg in your Django template (webdept/home/template/home/home.html), you need to ensure a few configurations are in place and use the appropriate template tags. Here's how you can do it: Configure MEDIA_URL and MEDIA_ROOT in your settings.py: # settings.py import os MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Set up your URL patterns to serve media files during development: # urls.py from django.conf import settings from django.conf.urls.static import static urlpatterns = [ # Your other URL patterns ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Access the image in your template using the MEDIA_URL context: First, ensure you load the static template tag at the top of your template: {% load static %} Then, you can use the MEDIA_URL to access your image: <img src="{{ MEDIA_URL }}image.jpg" alt="Image Description"> Example home.html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Home Page</title> </head> <body> … -
Problem in deploying django app using plesk
I am trying to deploy my django app and i am using plesk as a host. But i have 2 problems In order to reach the website instead of typing mydomain/login i have to type mydomain/templates/login.html The page appears broken as the picture below. I have checked and collected the static files and the urls seem fine. I don't understand what i am missing. I would appreciate a helping hand! Thank you -
postgres.fields.JSONField and models.JSONField
I have a model in some django project it has a JSONField in it. I want to connect to the table of that model from another django project so i copied the model from first django project and move it to second one. The first django project uses from django.contrib.postgres.fields import JSONField but i can't use same JSONField in second django project (because of django version in second project it does not support postgres.field.JSONField). My question is can i use from django.db.models import JSONField in second django project with no errors and connect to the same database? -
why my django save_model not saving manytomany relation
I'm having issues with ManytoMany Relationships that are not saving in a model when I save it (via the admin). i want to auto add title in tags. admin.py def save_model(self, request: Any, obj: Any, form: Any, change: Any) -> None: post = Fa.objects.get(id = obj.id) #return the current post fields for i in post.title.split(' '): try: t = FaTag.objects.get(title = i) post.tag.add(t) except: pass return super(FaAdmin,self).save_model(request, obj, form, change) when i print this line: obj.tag.all() it gives me the queryset that is currect but it wont save anything in database -
'django-admin' is not recognized as an internal or external command, operable program or batch file
Yesterday I installed Python and added it to PATH. Then I created a virtual environment using virtualenv. I then activated the environment and pip-installed django (using pip install django) and started a project by django-admin startproject project_name. Then I moved the virtual environment folder inside the project directory (formerly it was its sibling dirctory). I worked with the project and everything was fine until today when I opened it again. python manage.py runserver still does good but when I use django-admin commands it gives the error in the question title. It's not recognized but yesterday it was when I started the project (I did activate the environment again). The only difference from yesterday is that I upgraded pip. I looked up stackoverflow and it had plenty of questions for my problem but most of them had problem with PATH (which I had configured correctly and didn't have a problem with) or they had used django instead of django-admin or they were on Linux and had problems with sudo (but I'm on Windows 10). What can I do to solve this? -
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?