Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Docker Compose - The ImageField field in Django cannot upload images when I migrate the database from sqlite3 to MySQL in Docker Compose
I have the Article model in Django blog app File /backend/blog/models.py class Article(models.Model): class Status(models.TextChoices): DRAFT = 'DF', 'Draft' PUBLISHED = 'PB', 'Published' title = models.CharField(max_length=255) slug = models.SlugField(max_length=100, blank=True, unique=True) content = MDTextField(null=True, blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) comments = models.IntegerField(default=0) reactions = models.IntegerField(default=0) updated = models.DateTimeField(auto_now=True) category = models.ForeignKey(Category, related_name='articles', on_delete=models.SET_NULL, null=True) tags = models.ManyToManyField(Tag) image_background = models.ImageField(upload_to='articles_images/', blank=True, null=True) image_url = models.URLField(max_length=500, blank=True, null=True) # Updated field to store image URL from Firebase intro = models.TextField() estimate_time = models.CharField(max_length=50) type = models.ForeignKey(Type, on_delete=models.SET_NULL, null=True) publish = models.DateTimeField(default=timezone.now) status = models.CharField(max_length=2, choices=Status.choices, default=Status.DRAFT) Next, I porting the default database SQLITE3 to MYSQL for Django project File /backend/settings.py # ! Config database for mysql DATABASES = { "default": { "ENGINE": os.environ.get("SQL_ENGINE", "django.db.backends.sqlite3"), "NAME": os.environ.get("SQL_DATABASE", os.path.join(BASE_DIR, 'db.sqlite3')), "USER": os.environ.get("SQL_USER", "myuser"), "PASSWORD": os.environ.get("SQL_PASSWORD", "myuserpassword"), "HOST": os.environ.get("SQL_HOST", "localhost"), "PORT": os.environ.get("SQL_PORT", "3306"), 'OPTIONS': { 'charset': 'utf8mb4', } } } I also config the path media to upload image /backend/settings.py STATIC_URL = 'static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_DIRS = (os.path.join(BASE_DIR,"static"), ) I used the docker-compose.yml to build image and run container for backend (django), frontend (nextjs) and database (mysql) to develop my project version: '3.8' services: database: image: … -
django: unable to customise the admin history page
I want to display the old and new values in the history log page. I have been able to save the data and print it to the server but I cannot seem to customise the history page layout / rendering... it simply ignores my file. I have created a custom html file in the folder: project/app/templates/admin/app/modelname/history.html (project/api/templates/admin/api/apicustomer/history.html) after several hours of GPT i give up! Can andybody advise? -
Django populate Model form dynamically with model - possible?
I am trying to use a model form independently of the model that is passed. My goal is to have a list of database tables where the user can select the table which is then displayed. Then within this table there is the possibility to select a table entry which can be updated. There will be changing tables over time, therefore I want to use one model form to include all the fields for editing and just change the underlying Model. I tried some things and right now this is my "last" attempt that is not working. Any advice or guidance? This is in my views.py class DynamicModelForm(forms.ModelForm): class Meta: model = None fields = '__all__' # setting the model based on the input selection of user def get_dynamic_form(request, model, instance=None): DynamicModelForm.model = model DynamicModelForm.fields = '__all__' return DynamicModelForm(request.POST or None , instance=instance) # # # # in my class based view I am using this to list the tables def list(self, request, model, model_name): print(f'Pulling model {model_name}') objects = model.objects.all() fields = [field.name for field in model._meta.fields] # Retrieve field names self.context['fields'] = fields self.context['model_name'] = model_name self.context['objects'], self.context['info'] = set_pagination(request, objects) if not self.context['objects']: return False, self.context['info'] return … -
How to deploy a Django app on a Linux server on a home network such that it is only ever accessible by the people on the network?
How to deploy a Django app on a Linux server on a home network such that it is only ever accessible by people on the network? I have a Django app that I'd like to deploy on a Linux server, but I only want it to be accessible to devices within my home network (e.g., computers and mobile devices connected to the same Wi-Fi). I don't want it to be publicly accessible over the internet. I have the following setup: The Django app is running on a Linux server (Ubuntu 20.04). The server is connected to my home network via Ethernet or Wi-Fi. I want to ensure that the app can be accessed from devices on the same network but not from outside the network. What is the best way to deploy and configure this Django app to achieve the following? Restrict access to the home network: I want the app to only be accessible by devices that are physically connected to the home network (e.g., via Wi-Fi or Ethernet) and not exposed to the outside world. Web server configuration: Should I use Gunicorn or uWSGI with Nginx or Apache? How should I configure them to ensure proper security and … -
How to design a scalable messaging system with Celery, Redis, Django Channels, and FastAPI?
I am designing a scalable messaging system based also in Django, where users can exchange messages in real-time. Here are the key requirements and technologies I am planning to use: I plan to use Celery for background task processing, such as handling message delivery and notifications. Redis will act as the broker. I am considering a NoSQL database, such as MongoDB, to store messages due to its flexibility and scalability. Each message will have fields like message_id, sender_id, receiver_id, content, timestamp, and status. Just a single table approach. For real-time message delivery and user notification, I am exploring Django Channels or FastAPI with WebSockets. Caching Layer: Redis will also be used as a caching layer to improve performance for frequently accessed data, such as user notifications or unread messages. Scalability and Performance: The system should support up to 1,000 messages per second. It should handle over 10,000 concurrent users viewing messages simultaneously. Daily active users may exceed 100,000. My Questions: Is this architecture suitable for my requirements, or should I consider alternative technologies? At what scale should I start considering sharding my MongoDB database to handle the load efficiently? Would a load balancer (e.g., Nginx) suffice to handle the WebSocket … -
Django and Gunicorn setup
I followed this video https://www.youtube.com/watch?v=NSHshIEVL-M and ran into problems when trying to curl the webpage. I thought it might be a firewall issue but since I'm running the curl command locally would that be an issue? I also ran which gunicorn from inside my environment and populated that the in the gunicorn.service file under ExecStart. I have shared my configs below any help is appreciated! django setup: Gunicorn config: gunicorn.service curl command output -
How to validate Django models with foreign key relationships before saving any records?
I am working on a Django project where I need to validate a model before saving it, based on values in its related models. I came up with this issue while extracting an app from an project using an old Django version (3.1) to a separate Django 5.1 project, then there error "ValueError: 'Model...' instance needs to have a primary key value before this relationship can be used" raised on all validation classes that used related model data. For demonstration and simplification purposes, I have a Reservation model that references multiple Guest objects via a foreign key. For the reservation to be valid and be saved, all guests linked to it must be at least 18 years old. However, none of these records (neither the reservation nor the guests) have been saved to the database yet. I need to perform this validation efficiently and cleanly, preferably in a way that keeps the validation logic separated from the models themselves. How can I approach this validation scenario? What are the best practices for validating unsaved foreign key relationships in Django? Here is a simplified version of my setup: File: models.py from django.db import models class Reservation(models.Model): check_in_date = models.DateField() check_out_date = … -
No module named 'psycop'. Cannot make migrations
I'm trying to get a login page not to return a 500 error, and have been trying to migrate my database. I have installed psycopg2 correctly (I believe), but I think I have not got the correct NAME in DATABASES at settings.py. Here is what I have: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': BASE_DIR / 'db.postgresql', } } Would somebody know if what I have in 'NAME' is correct, or what else I should put in there? Thank you. -
Why ValueError is not handled upon my Django Middleware?
I am Implementing a Basic view that raises a ValueError: from rest_framework.views import APIView from django.http import HttpResponse class ThreadView(APIView): def get(self, request, *args, **kwargs): limit = int(request.GET.get('limit', 10)) if limit < 0: raise ValueError("Limit must be a positive number") return HttpResponse("OK",200) And I made a simple middleware as well: from django.http import JsonResponse class ErrorMiddlewareHandler: """ Custom middleware to handle Errors globally and return a standardized JSON response. """ def __init__(self, get_response): self.get_response = get_response def __call__(self, request): try: # Process the request and pass to the view response = self.get_response(request) except ValueError as v: print("mIDDLEWARE ",v) response = JsonResponse({'msg': str(v)}, status=400) # You can change status as needed except Exception as e: response = JsonResponse({'msg': "Internal Error occired"}, status=500) return response I registered it into settings.py: 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', 'assistant_api.middleware.ErrorMiddlewareHandler.ErrorMiddlewareHandler', # <<< This One ] But it seem middleware not to be able to handle it: Despite being registered into middlewares. Do you know why??? -
Django Admin: How to hide nested inline until parent is saved?
I have a nested inline setup in Django Admin where I want to hide a child inline until its parent is saved. Here's a simplified version of my models: class Parent(models.Model): name = models.CharField(max_length=255) class Child(models.Model): parent = models.ForeignKey(Parent, on_delete=models.CASCADE) name = models.CharField(max_length=255) class GrandChild(models.Model): child = models.ForeignKey(Child, on_delete=models.CASCADE) name = models.CharField(max_length=255) And here's my admin setup: class GrandChildInline(NestedTabularInline): model = GrandChild extra = 0 def get_formset(self, request, obj=None, **kwargs): formset = super().get_formset(request, obj, **kwargs) return formset class ChildInline(NestedTabularInline): model = Child extra = 0 inlines = [GrandChildInline] class ParentAdmin(NestedModelAdmin): inlines = [ChildInline] admin.site.register(Parent, ParentAdmin) Current Behavior When editing a Parent, I can add Children The GrandChild inline is visible immediately when adding a new Child I want the GrandChild inline to only appear after the Child is saved Desired Behavior GrandChild inline should be hidden when adding a new Child GrandChild inline should only appear after the Child is saved GrandChild inline should be visible when editing an existing Child What I've Tried Using the template property to return an empty string Using has_add_permission and get_queryset Checking for parent instance existence None of these approaches fully work - either the inline is always visible or always hidden. Question How … -
Django fails to correctly link viewable documents stored in a Django model
So I currently have a Django model which correctly references everything passed to my template, except for the link to the document I have uploaded. The model has been correctly registered in admin.py. Here is is MRE: #investors/models.py from django.db import models class FinancialStatements(models.Model): financials_upload = models.FileField(upload_to='documents/financials/') class Meta: verbose_name_plural = "Financial Statements" #investors/views.py from .models import FinancialStatements def investor_relations(request): financials_queryset = FinancialStatements.objects.all() context = { 'financials_queryset' : financials_queryset, } return render(request, 'investors.html', context) #settings.py MEDIA_URL = '/assets/' MEDIA_ROOT = BASE_DIR / 'assets' #investors/templates/investors.html {% for financials in financials_queryset %} <a href="{{financials.financials_upload.url}}">Financial Statement</a> {% endfor %} Upon accessing the uploaded file from the model, the URL is http://127.0.0.1:8000/assets/documents/financials/<filename>.pdf which is the directory I want to specify, and so is correct. However, Django is continuing to fail to access the URL from {{financials.financials_upload.url}} when looping through the financials_queryset quertset My file directory is set up in the following fashion: <ROOT>/assets/documents/financials/** Whenever I hover over the <a> tag, the message in the bottom of the left corner of the browser fails to return the URL of the document to be viewed. It simply returns http://127.0.0.1:8000/investors Despite this, I do fail to see how cannot work this one out, despite correctly point it … -
Settings.py cannot find psycopg2... squlite3 and postgresql problem... no such table: auth_user
I'm trying to deploy a simple app (learning log from Python Crash Course) to heroku. The app runs but upon login, I get a 500 error, and in debug=true the error is: no such table: auth_user. I realise this has something to do with squlite3 and Postgresql, but when I try to build the code in settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': BASE_DIR / 'db.sqlite3', } } the error message is ImportError: DLL load failed while importing _psycopg: The specified module could not be found. I have attempted to install and import psycopg2, and it appears to be in requirements.txt. But I think the paths are not aligning, since psycopg2 is in a python pathway, and setting.py is looking in my project environment. I'm very confused! Please help! -
Why am I getting a 403 Forbidden error when making a POST request to the login API in Vue.js?
I'm working on a Vue.js application where users can log in through an API using the axios library. However, when I send a POST request to the API endpoint, I'm getting a 403 Forbidden response. Here's the Vue.js code for the login request: const response = await axios.post( 'https://apibackup.example.com/api/login/', { username: email.value, password: password.value }, { headers: { 'Content-Type': 'application/json' }, withCredentials: true, withXSRFToken: true } ) And here's the login view from the Django backend: def login_view(request): if request.method == 'POST': try: data = json.loads(request.body) form = LoginForm(data) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) # Logic for handling user types here... else: return JsonResponse({'status': 'error', 'message': 'Invalid username or password'}, status=401) else: return JsonResponse({'status': 'error', 'errors': form.errors}, status=400) except json.JSONDecodeError: return JsonResponse({'status': 'error', 'message': 'Invalid JSON data'}, status=400) Here are the relevant settings from the Django settings.py: CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = [ 'https://example.com', 'http://localhost:5173', # other domains... ] CSRF_TRUSTED_ORIGINS = [ 'https://example.com', 'http://localhost:5173', # other domains... ] CSRF_COOKIE_SAMESITE = 'None' CSRF_COOKIE_SECURE = True CSRF_COOKIE_DOMAIN = 'example.com' Issue: When I try to log in, I get the following error in the browser console: POST https://apibackup.example.com/api/login/ … -
AxiosError: Network Error on iOS (GET request ) with Expo, working fine on Android
it's first time i am asking question in stack overflow . I hope you this will help me to solve the issue. About project I am using expo and axios for api request use hooks for handling the request using Django as backend Problem Overview Api request (all type of request) working properly in Android and Web In IOS the POST request working properly But Get request not working Getting this error when request get request from IOS "AxiosError: Network Error" I tested the Get request in IOS with other API tester app in IOS then it worked fine Expo App some codes app.json { "expo": { "name": "MyWard", "platforms": [ "ios", "android" ], "scheme": "com.myward", "slug": "myward", "version": "1.0.0", "orientation": "portrait", "icon": "./assets/images/logo/thumbnail.png", "userInterfaceStyle": "automatic", "ios": { "bundleIdentifier": "com.myward", "supportsTablet": false, "jsEngine": "jsc", "infoPlist": { "LSApplicationQueriesSchemes": ["whatsapp"] }, "runtimeVersion": { "policy": "appVersion" } }, "splash": { "image": "./assets/images/logo/thumbnail.png", "backgroundColor": "#ffffff" }, "jsEngine": "hermes", "android": { "package": "com.myward", "googleServicesFile": "./android/app/google-services.json", "runtimeVersion": "1.0.0" }, "web": { "bundler": "metro", "output": "static", "favicon": "./assets/images/logo/thumbnail.png" }, "plugins": [ "expo-router", "expo-localization", [ "expo-build-properties", { "android": { "usesCleartextTraffic": true } } ] ], "experiments": { "typedRoutes": true }, "extra": { "router": { "origin": false }, "eas": … -
How to Add a Python Interpreter to a Web Application?
I am currently working on a Learning Management System (LMS) web app, and one of the features I need to implement is a web-based Integrated Development Environment (IDE) where users can write, execute, and test Python code directly in the browser. What I am looking for: Guidance on integrating a Python interpreter into the web app. Best practices for securely running user-submitted Python code to prevent malicious activities. Recommendations for tools, libraries, or APIs that can help execute Python code. How to handle input/output in the IDE and display results to the user in real-time. Key considerations: The web app is built using Django and react. Code execution should be sandboxed for security. The IDE should be able to handle basic Python scripts and display outputs/errors to users and suggestions too. -
Does anyone have any ideas on how to make django multilingual more elegant and easier to maintain? [closed]
I had to realize that implementing multilingualism in Django turns out to be an absolute pain. I have seen the following variants, which are absolutely subterranean: Language via Excel. As I said, the message files. This also includes Django-Rosetta, which is a kind of management interface for the message files. And last but not least json files. Unfortunately, that doesn't make it any better for me. Does anyone have any ideas on how to make this more elegant and easier to maintain? Is there an extension that compares the languages like ResXManager Extension in Visual Studio? Thanks in advance. -
How to change the appearance of the TextField in the Django admin?
I want to increase the size of the text area in django admin form. html_content = models.TextField() -
WebSocket (python server, javascript/rxjs client) missing messages
Introduction I'm trying to provide as much info up front, so if I've missed something, please let me know. Motivation: server does the work (asyncio with multi-processing), client just requests and presents data. WebSockets (herein WS) used primarily to minimize latency of requests and replies (connection protocols done up front, and TLS connection done once). WS uses TCP, which has produced sufficiently transparent transactions...no need for UDP or anything for greater speed. Setup WS server: Python/Daphne/Django Channels (updated) WS client: Javascript/Angular/Rxjs (updated) Both running on localhost (no physical throughput contention, ) Applications Client: Angular, primarily requesting and formatting data for presentation Server 1: Django channels async JSON consumer (asyncio framework...maybe important later). Server 2: Python using WebSockets pypi asyncio package (currently legacy...will address later...confirmed not the issue). Server 1 instance connects to server 2 TLS WS connection. Problem I implemented the servers a few years ago. Long story short: I was seeing some aspects of latency in places I didn't expect when using await with the Django ORM. Short answer? I just switched the DB connections from database_sync_to_async to wrapping the calls in asyncio.to_thread. The concurrency experienced has improved by a factor of 10 without a doubt, as I was … -
'django-admin startproject myproject' is not recognised
django-admin : The term 'django-admin' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 django-admin startproject myproject + CategoryInfo : ObjectNotFound: (django-admin:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException i tried running this django-admin startproject myproject -
How to get information out of 'OneToOneField' and use this information in admin.py list_display?
I making my first site, this is my first big project so I stuck at one issue and can't solve it.. Here part of my code with error: models.py ... class GField(models.Model): golf_club_name = models.CharField( primary_key=True, max_length=100, help_text='Enter a golf club (Gfield) name', ) golf_field_par = models.PositiveIntegerField() def __str__(self): return f'{self.golf_club_name}' class PlayerInstance(models.Model): ... golf_field_playing = models.OneToOneField(GField, default = 'for_nothoing',on_delete=models.RESTRICT, help_text='where is it taking part?') now_at_hole = models.IntegerField() today = models.IntegerField() R1 = models.IntegerField() R2 = models.IntegerField() R3 = models.IntegerField() R4 = models.IntegerField() R5 = models.IntegerField() all_rounds = [R1, R2, R3, R4, R5] counter = sum(1 for value in all_rounds if value != 0) par_value = gfield_playing.golf_field_par total = sum(all_rounds[:counter]) if par_value * counter <= total: to_par = f'+{total - par_value * counter}' if par_value*counter>total: to_par = f'-{par_value * counter - total}' ... When I saving this code it sending: par_value = gfield_playing.field_par ^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'OneToOneField' object has no attribute 'field_par' And about admin.py that sending error, when I tried some solves from internet, I actually made the 'to_par' well, and fixed Error: models.py ... R2 = models.IntegerField() R3 = models.IntegerField() R4 = models.IntegerField() R5 = models.IntegerField() def calculate_to_par(self): all_rounds = [self.R1, self.R2, self.R3, self.R4, self.R5] counter = sum(1 for … -
Deployed Django project on vercel can't see tables on the database
I have deployed a django project through vercel and my log in and sign up authentication can't seem to go through. The error shows that the table where I store my users, are not visible to the vercel deployed app. But when I try the project locally, the project works fine with no errors in the log in sign up. Here's the error deployed project error Message. Here's the Github Repository as well. I tried re-configuring my django project to make it vercel ready and also tried to change database host (I am using postgreSQL initially from Railway to Supabase) -
Django Admin Action Function Failing - emailing multiple selected users (if "apply" in request.POST)
My implementation uses a CustomUser model. I'm creating a Django admin action that allows me to compose and send emails to multiple users. Everything on the website behaves as though it's working. After I hit the Send Email button, I'm redirected back to the Admin but I see no console output indicating an email was sent and self.message_user is never called and sent to the Admin. Email Backend Password Reset works with reset link sent to the console, so email backend is working. EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend" admin.py if "apply" in request.POST: <-- This line never fires! class CustomUserAdmin(ExportMixin, UserAdmin): @admin.action(description="Email selected users") def send_email_action(self, request, queryset): print(request.POST) print(request.POST.getlist("apply")) input("HALT") if "apply" in request.POST: print("apply") form = EmailForm(request.POST) if form.is_valid(): print("form valid") subject = form.cleaned_data["subject"] message = form.cleaned_data["message"] recipients = [user.email for user in queryset] send_mail(subject, message, "your_email@example.com", recipients) self.message_user(request, f"{len(recipients)} emails were sent.") return HttpResponseRedirect(request.get_full_path()) else: print("no apply") form = EmailForm() return render(request, "email/admin_send.html", {"form": form}) forms.py Works as expected. class EmailForm(forms.Form): subject = forms.CharField(max_length=256) message = forms.CharField(widget=forms.Textarea) admin_send.html Either: The send_email_action function is getting called after I hit the Send Email button but the form isn't sending back the "apply" data, so this is failing: if "apply in request.POST: … -
I have a product and a category model. Now I should filter the products according to the category. How can I do it?
where should i code? at views.py or at the html file? actually I have an idea to render every category and inside that i should filter the products according to it. like, VEGITABLES carrot tomato FRUITS apple mango SOMETHING ELSE something 1 something 2 -
The problem of importing a model into consumer django Websockets
I want to write a consumer for the application, however, after importing the Device model, the application does not even want to start, crashes with an error that it cannot find the application settings. # consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer # from devices.models import Device class DeviceConsumer(AsyncWebsocketConsumer): async def connect(self): self.device_id = self.scope['url_route']['kwargs']['device_id'] print(self.device_id) await self.accept() async def disconnect(self, close_code): await self.close() async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] print(message) await self.send(text_data=json.dumps({'message': message})) And here are the Device and User models: from django.db import models from users.models import User from core.base.utils import generate_uuid class Device(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=255) device_key = models.CharField(max_length=255, unique=True, default=generate_uuid) is_active = models.BooleanField(default=True) def __str__(self): return self.name from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.timezone import now from django.utils.translation import gettext_lazy as _ class User(AbstractUser): first_name = models.CharField(_("first_name "), max_length=60, blank=False) last_name = models.CharField(_("last_name "), max_length=60, blank=False) username = models.CharField(_("username"), max_length=60, unique=True) email = models.EmailField(_("email address"), max_length=255, blank=False, unique=True) is_staff = models.BooleanField( _("is staff"), default=False, help_text=_("Determines whether the user can log in to this administrative site."), ) is_active = models.BooleanField( _("is active"), default=True, help_text=_( "Indicates whether this user should be considered active." "Uncheck this box instead … -
Polars Read Excel file from Form (ie. request.FILES.get('file'))
All the Polars examples show reading an Excel file from a path string. df = pl.read_excel("docs/assets/data/path.xlsx") But I am passing in the Excel file from a Django Form Post. file_name = request.FILES.get('file') df = pl.read_excel(file_name) I am getting a "InvalidParametersError". How do input the file to Polars from a HTML form? or do I somehow have to get the path from the request.FILES and use that? I am new to the whole Polars thing but very excited to try it. thank you.