Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Airtime/Data via APIs
I have a website that sales data and airtime together with TV subscriptions and electric bill payment. I used third party APIs to send airtime/data of network like MTN,aitel, Glo and Etisalat to users. The problem is their discount is very small and I barely make $5 a month Wich is affecting my site maintenance. I want to know is there is a way I can buy these services directly from these networks and not via third party APIs I used Python (Django) for the sites backend and react js for the frontend -
Query elements by attribute of Foreignkey Relation and also Query Foreign attributes most efficient
There are three models Product: Having an id, a name Storage: Having an id, a name, a color and a branch ProductStorage: Maps each Product to a Storage and has some extra attributes. I want to list all ProductStorages with a specific Storage.branch value grouped by the Storage, displaying storage name and color too. Is it possible to do this in one query? I am new to Django and I am unsure how to do this in the most efficient way. I know that I could query all ProductStorages and filter by branch. Then sort them maybe afterwards by their storages and query the storage-attributes in a second query. But I guess this won't be the best way to do it. -
In Django how to define test database and keep records inserted in test database until cleaned in tearDown method of testcase
I want a test database created for my default database in Django latest version, for that I configured in project settings.py file as below. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', 'TEST': { 'NAME': BASE_DIR / 'test_db.sqlite3', } } } I have a model Topic in my models.py file and have run makemigrtions & migrate cmds to have table in sqlite db. I have created TestTopic class in my app(first_app) tests.py file as below from django.test import TestCase,SimpleTestCase from .models import Topic class TestTopic(TestCase): def setUp(self): Topic.objects.create(top_name='Test topic1') Topic.objects.create(top_name='Test topic2') Topic.objects.create(top_name='Test topic3') def test_create_topic(self): all_topics = Topic.objects.count() self.assertEqual(all_topics, 3) def tearDown(self) -> None: return super().tearDown() I am executing cmd below to run my app(first_app) tests. Passing --keepdb for preserving test_db. py manage.py test first_app --keepdb After this I see test case pass. But when I am checking test_db.sqlite in sqlite db browser app to see test topics I created in test case, I do not see them. I want to have those records in test_db until I clear them manually or in tearDown method of my test case. ( Below is sqlite db browser of test_db.sqlite topics table. -
Django Channels: Connection gets accepted, loads initial messages, but no new messages are being sent via the channel
I have a Django Channels consumer class. The WebSocket connection establishes without any issues, and initial messages are also loaded. However, when I try to send a message, it does not trigger the async_to_sync method and the chat_message function. I have attempted this multiple times. The print statement inside the chat_message function is not working, and although I tried catching exceptions, there are no errors as well. I have checked the channel layer and Redis through the shell, and they are working fine. New messages are created in the backend, and notifications are received, but no message is being sent to the client side. class ChatConsumer(WebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.user = None self.room_group_name = None self.room_code = None def connect(self): self.room_code = self.scope['url_route']['kwargs']['room_code'] self.room_group_name = f'chat_{self.room_code}' self.room = get_object_or_404(ChatRoom, room_code=self.room_code) try: try: self.user = self.scope['user'] except Exception as e: self.user = None if self.user == None: self.close() return # Join room group self.channel_layer.group_add( self.room_group_name, self.channel_name ) self.accept() self.load_initial_messages() except Exception as e: print(str(e)) self.close() def disconnect(self, code): async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) def receive(self, text_data=None): text_data_json = json.loads(text_data) message = text_data_json['message'] msg = Message.objects.create(room=self.room, user=self.user.username, message=message,) message_data = { 'roomCode': self.room_code, 'user': msg.user, 'message': msg.message, } try: async_to_sync(self.channel_layer.group_send)( … -
Getting CORS Error for only DELETE Request (Have no issues with PUT, POST and GET) DRF and React project
I have been facing this following error whenever I make the request from my react.js frontend. I am using django DRF on backend and nginx as reverse proxy. Both are deployed in gcp cloud run as different services. Meaning frontend and backend are in different origins, that prompted me to enable the CORS policy. I am fairly new to both of the technologies. Access to XMLHttpRequest at 'https://backend-service/api/employee/' from origin 'https://frontend-service' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. The weird part is, it's throwing the above error but the item is getting deleted in the database. My views.py, @api_view(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']) def handle_crud_operations(request, SerializerClass): if not SerializerClass: return Response({'message': 'Invalid serializer specified'}, status=status.HTTP_400_BAD_REQUEST) # GET method to retrieve all objects of the specified model if request.method == 'GET': model_objects = SerializerClass.Meta.model.objects.all() serializer = SerializerClass(model_objects, many=True) return Response({'message': 'Successfully retrieved data', 'data': serializer.data}, status=status.HTTP_200_OK) # POST method to create a new object elif request.method == 'POST': serializer = SerializerClass(data=request.data) if serializer.is_valid(): serializer.save() return Response({'message': f'{SerializerClass.Meta.model.__name__} created successfully', 'data': serializer.data}, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) # PUT method to update an object (full update) elif request.method == 'PUT': obj = get_object_or_404(SerializerClass.Meta.model, pk=request.data.get('id')) serializer … -
Django - FOREIGN KEY constraint failed
In this part of the code for syncing an excel sheet to the database: for record in lesson_records: try: date = parser.parse(record['Date']).date() start_time = parser.parse(record['Start Time']).time() end_time = parser.parse(record['End Time']).time() primary_tutor = get_object_or_404(Staff, gmail=record['Primary Tutor Email']) logger.info(primary_tutor) course = get_object_or_404(Course, course_code=record['Course Code']) logger.info(course) lesson, created = Lesson.objects.update_or_create( lesson_code=record['Lesson Code'], defaults={ 'course_code': course, 'date': date, 'start_time': start_time, 'end_time': end_time, 'lesson_no': record['Lesson Number'], 'school': record['School / Customer'], 'teacher': record['Teacher'], 'teacher_contact': record['Teacher Contact'], 'venue': record['Venue'], 'remarks': record['Remark'], 'delivery_format': record['Delivery Format'], 'primary_tutor': primary_tutor } ) logger.info(record['Lesson Code']) except Exception as e: lesson_errors.append(f"Error in Lesson {record['Lesson Code']}: {str(e)}") logger.error(f"Error in {record['Lesson Code']}: {str(e)}") I recieve a Error in [course code]: FOREIGN KEY constraint failed for every single course. The primary_tutor and course are both correctly logged, so both get_object_or_404 succeeded and they both exists in the database, but it still failed the foreign key constraint. This is the model: class Lesson(models.Model): course_code = models.ForeignKey(Course, on_delete=models.CASCADE) date = models.DateField() start_time = models.TimeField() end_time = models.TimeField() lesson_no = models.IntegerField() lesson_code = models.CharField(max_length=20, primary_key=True) school = models.CharField(max_length=100) teacher = models.CharField(max_length=10) teacher_contact = models.CharField(max_length=100) teacher_email = models.EmailField(blank=True, null=True) venue = models.CharField(max_length=100) remarks = models.TextField(blank=True, null=True) delivery_format = models.CharField(max_length=10) primary_tutor = models.ForeignKey(Staff, on_delete=models.CASCADE, related_name='primary_tutor') other_tutors = models.ManyToManyField(Staff) calender_id = models.CharField(max_length=100, … -
xhtml2pdf when works with a parsed table or content div breaks <li> numeration
I need to create pdf document with xhtml2pdf. Everything is great with html, but pdf document breaks the numeration while working with tables or parsed div containers. pdf html I've tried to change that block to many divs and the numeration returned, but it didn't look like something I've needed. But when I changed formatting to the way I want, the numeration disappeared again. Can't understand the reason of this behaviour. -
How to catch failed rows during the bulk_create in Django?
I process large CSV, Excel files and save result using Django bulk_create method. But some of rows may have corrupted data and in that case all rows will not be saved to database. Ideally I want to catch failed rows and show users which rows are failed to save. Then users can make decision whether skip failed rows or upload new file. I try to catch failed rows during the bulk_create in Django. -
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.