Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Best practice to switch between development and production urls when using Vue/Vite and Django
I want to build a website with Vue/Vite as frontend and Django as a backend. When my frontend needs to get data from the backend I currently do something like this (which works perfectly fine): const response = await fetch('http://localhost:8000/api/register', {... But for a production environment I (probably?) want something like this to be able to switch between dev and prod without manually changing every url: const response = await fetch(backend_url + '/register', {... My Question is, what is the best/standard way to setup this backend_url in Vue/Vite? Kind regards feps My Search so far: Vue has a provide/inject feature which could be used to define a gloable Variables in my App.vue file. Vite has "Shared options" defined in vite.config.js But for both options I was unable to find any example, which leaves me wondering if there is another option which I was unable to find, which is used to solve this "problem". -
How to disable Celery startup logs?
I'm getting a bunch of logs like this: [2025-11-29 16:13:15,731] def group(self, tasks, result, group_id, partial_args, add_to_parent=0): return 1 [2025-11-29 16:13:15,732] def xmap(task, it): return 1 [2025-11-29 16:13:15,732] def backend_cleanup(): return 1 I don't need these logs. It's useless spam to me. How do I disable this? -
Problem connecting djangoapi with react native mobile with django api
This is my first time here asking for help!!!, My name is Pedro, is a pleasure to be here. So. I made a system to help the company with a task work, and hopefully, be noticed to work with the development team. One of things that's mandatory is the being able to use it on mobile. The back end was made using django, and I've created a API with django rest framework, I've tried to create a mobile application with React Native that consumes the API, but every time I try to use the API I get the 401 error, and I can't find the mistake. Could someone please help my find it? -
Filter dates using foreignkey Django and Python
I need to filter a variable between two models using a foreign key. models.py class Vuelo(models.Model): fecha_de_vuelo = models.CharField(max_length=50) ....... class Novedad(models.Model): fecha_de_vuelo_novedad = models.ForeignKey(Vuelo, on_delete=models.CASCADE, related_name="fecha_de_vuelo_novedad", null=True, editable=False) comandante_novedad = ...... view.py def buscar_reporte_demoras(request): if request.method == "GET": inicio = request.GET.get("fecha_inicio", None) fin = request.GET.get("fecha_fin", None) criterio_1 = Q(fecha_de_vuelo_novedad__fecha_de_vuelo__gte = inicio) criterio_2 = Q(fecha_de_vuelo_novedad__fecha_de_vuelo__lte = fin) busqueda = Novedad.objects.all() busqueda_con_filtro_fechas = busqueda.filter(criterio_1 & criterio_2) context = { 'lista_vuelos': busqueda_con_filtro_fechas, 'criterio_fecha_inicio': inicio, 'criterio_fecha_fin': fin, } return render(request, '.........html', context) The problem is that when I try to filter by "fecha_de_vuelo" using related_name = "fecha_de_vuelo_novedad" it doesn't give me any results. What would the error be? Thank you for your help. -
Filter dates using foreignkey Django
I need to filter a variable between two models using a foreign key. models.py class Vuelo(models.Model): fecha_de_vuelo = models.CharField(max_length=50) ....... class Novedad(models.Model): fecha_de_vuelo_novedad = models.ForeignKey(Vuelo, on_delete=models.CASCADE, related_name="fecha_de_vuelo_novedad", null=True, editable=False) comandante_novedad = ...... view.py def buscar_reporte_demoras(request): if request.method == "GET": inicio = request.GET.get("fecha_inicio", None) fin = request.GET.get("fecha_fin", None) criterio_1 = Q(fecha_de_vuelo_novedad__fecha_de_vuelo__gte = inicio) criterio_2 = Q(fecha_de_vuelo_novedad__fecha_de_vuelo__lte = fin) busqueda = Novedad.objects.all() busqueda_con_filtro_fechas = busqueda.filter(criterio_1 & criterio_2) context = { 'lista_vuelos': busqueda_con_filtro_fechas, 'criterio_fecha_inicio': inicio, 'criterio_fecha_fin': fin, } return render(request, '.........html', context) The problem is that when I try to filter by "fecha_de_vuelo" using related_name = "fecha_de_vuelo_novedad" it doesn't give me any results. Cual seria el error? Agradezco la ayuda -
Paystack integration with Django
I'm trying to integrate paystack into my django E-commerce but I keep getting this error, ❌ Order creation error: [WinError 10061] No connection could be made because the target machine actively refused it, when i try to checkout. Can anyone please help me? -
My password field and confirm_password field are not being validated as expected except through my view
I am working on a practice project for a P.A.Y.E system. My layout template, home page template, navbar template are located at project level. While my registration template is at app level in my django project. I wrote code in models.py (located at app level) for PAYEAgent class like so: from django.db import models from django.contrib.auth.hashers import make_password, check_password # Create your models here. class PAYEAgent(models.Model): payer_id = models.CharField(max_length=100, primary_key=True) agent_name = models.CharField(max_length=255, unique=True) agent_rc_num = models.CharField(max_length=50, unique=True) contact_email = models.EmailField(unique=True) contact_phone = models.CharField(max_length=20) address = models.TextField() agent_password = models.CharField(max_length=128) registration_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.agent_name def check_password(self, raw_password): return check_password(raw_password, self.agent_password) In my forms.py, the code goes thus: from django import forms from . import models class PAYEAgentForm(forms.ModelForm): agent_password = forms.CharField(max_length=128, widget=forms.PasswordInput) confirm_password = forms.CharField(max_length=128, widget=forms.PasswordInput) class Meta: model = models.PAYEAgent fields = ['payer_id', 'agent_name', 'agent_rc_num', 'contact_email', 'contact_phone', 'address', 'agent_password'] def clean_payer_id(self): payer_id = self.cleaned_data.get('payer_id') if models.PAYEAgent.objects.filter(payer_id=payer_id).exists(): raise forms.ValidationError("Payer ID already exists.") return payer_id def clean_agent_password(self): password = self.cleaned_data.get('agent_password') if len(password) < 8: raise forms.ValidationError("Password must be at least 8 characters long.") return password def clean_confirm_password(self): confirm_password = self.cleaned_data.get('confirm_password') if len(confirm_password) < 8: raise forms.ValidationError("Confirm Password must be at least 8 characters long.") return confirm_password def clean(self): cleaned_data … -
How do I make a custom field output different datatypes depending on file asking for data?
I'm building a molecule properties displaying website using django and sqlite. The database takes a numpy array and stores it as a BLOB. Currently, it just outputs the numpy array back out when asked for it. I'd like it to check what kind of file is asking the data, and output a numpy array if python is asking for it ( for instance for a data integrity test ), and a json object if requested by a javascript file ( like for molecule visualization ). I'm not even sure if it's possible, so I guess my question is twofold. One, is it possible? Two, if it's not, as long as the data is read only, are there any major problems that might come up if I let inputs be as numpy arrays, and outputs be as json. The custom field is defined as so: The packages used: import io import json import numpy as np from django.db.models import BinaryField from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ For the current numpy only implementation: # Stores numpy array as BLOB then returns BLOB as np array class NpArrayField(BinaryField): """ Turns numpy array into raw binary data to store in … -
API request tracing with NextJS, Nginx and Django
I’m trying to measure the exact time spent in each stage of my API request flow — starting from the browser, through Nginx, into Django, then the database, and back out through Django and Nginx to the client. Essentially, I want to capture timestamps and time intervals for: When the browser sends the request When Nginx receives it When Django starts processing it Time spent in the database Django response time Nginx response time When the browser receives the response Is there any Django package or recommended approach that can help log these timing metrics end-to-end? Currently I have to manually add timestamps in nginx conf file, django middleware, before and after the fetch call in the frontend. There is Datadog but for now I want a django lightweight solution. Thanks! -
Django Using High Memory [closed]
I am running a smallish Django web app on a digital ocean droplet. I access via a safari browser on my laptop. I've noticed the app slowing down a bit recently and when I look in the activity monitor I notice that it's running at 4.05GB of memory constantly. That is the highest of any service on my laptop including AutoCAD, office, email etc. Is there something wrong with this, or has Django just blocked out the memory. Surely a Django app should be using a kB of memory? The processing isn't happening locally, only the rendering of the templates, front end services? How do I diagnose this? -
get the data from the server with fetch API
i get the data from the server with fetch API it contains html, when i click on load more posts button it should load the html at the bottom of the page we got from the server, but it also loads the headers we wrote for the current page(posts-list) and even other elements from scratch every time, while i didn`t write anything other than the posts we should receive. if we have selected to load more posts, it will load the post-fragment at the bottom of the current page. it does this, but it also reads the template tag from the posts list that contains headers. in general, every time a post-fragment is sent from the server, the current page is read from the first line along with the posts we received from the post-fragment, but we defined in the view that if the request was of XML type, only send the post-fragment. views.py def post_list(request): posts = Post.objects.all() page = request.GET.get('page') paginator = Paginator(posts, 1) try: posts = paginator.page(page) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = [] if request.headers.get("x-request-with") == "XMLHttRequest": return render(request, "social/posts-fragment.html", {"posts": posts}) context = {'posts': posts} return render(request, "social/posts-list.html", context) posts-list(current page) {% … -
pipfile.lock error while installing mysqlclient on macos 12 . can i get any help from you?
Your dependencies could not be resolved. You likely have a mismatch in your sub-dependencies. You can use $ pipenv run pip install <requirement_name> to bypass this mechanism, then run $ pipenv graph to inspect the versions actually installed in the virtualenv. Hint: try $ pipenv lock --pre if it is a pre-release dependency. ERROR: Failed to lock Pipfile.lock! -
How should I structure a Django backend with a Vue 3 frontend for a news application?
I’m building a small “newsroom” application where Django handles the backend (API, authentication, admin) and Vue 3 handles the frontend UI. I’m still fairly new to combining Django with a modern JavaScript framework, and I’m running into questions about the correct project structure. My goal is: Django provides a REST API Vue 3 (with Vite) is the standalone frontend The frontend and backend will be deployed separately later Local development should be simple, with minimal configuration Right now my folder structure looks like this: newsroom/ backend/ manage.py newsroom/ settings.py urls.py articles/ models.py views.py serializers.py frontend/ src/ vite.config.js package.json I’m unsure if this is considered a good pattern or if there are better ways to organize a Django + Vue project where the frontend is completely decoupled. I also want to make sure this structure won’t cause problems when I start working with authentication and serving the built Vue files in production. My questions: Is this a clean and maintainable structure for a Django + Vue 3 project, or should the frontend be inside the Django project folder? When deploying, is it better to serve Vue separately as its own static site, or build the Vue app and let Django serve … -
Nginx not serving static files
Hi everyone I am trying to upload a application using Nginx, Gunicorn, Django application run fine in development environment but for production it does not serves static files. I tried hard but failed to find any solution so I am posting here.Here is my NGINX configuration Here is my settings.py Here are the results of running python manage.py collectstatic no problem all static files are collected properly Here are all the templates and html files those I am using some more more html Here is the full directory structure of my project why Nginx is not accessing 'root' directory when I am collecting all static files into it. it accesses 'static' directory and throws following errors in the error log why it is not accessing root directory that is suppose to have permissions for access -
Restarting backend container became unreachable for traefik(504 Gateway timeout)
I’m having a problem and I can’t find a solution. I have deployed a Django backend and a React frontend using Docker. I’m using Traefik as a reverse proxy for the web server. When I start Traefik, the backend, and the frontend, everything works perfectly. However, when I try to upgrade my apps, the backend becomes unreachable (504). To fix it, I have to restart Traefik and then start the backend after Traefik. After that, it works again. This is my backend Docker Compose: services: backend: image: backend-v3:latest container_name: dashboard-backend restart: always env_file: - ./dashboard/.dockerenv volumes: - .:/app - ./infra/static:/app/staticfiles networks: - traefik - db_network ports: - "8000:8000" labels: - "traefik.enable=true" - "traefik.http.routers.django-api.rule=Host(`domain.com`)" - "traefik.http.routers.django-api.entrypoints=websecure" - "traefik.http.routers.django-api.tls=true" - "traefik.http.routers.django-api.tls.certresolver=myresolver" - "traefik.http.services.django-api.loadbalancer.server.port=8000" healthcheck: test: ["CMD-SHELL", "python3 -m urllib.request http://localhost:8000/health/ || exit 1"] interval: 10s timeout: 5s retries: 5 networks: traefik: external: true db_network: external: true And this is how I start Traefik: #!/bin/bash docker run -d \ --name traefik \ --network traefik \ --restart=always \ -p 80:80 \ -p 443:443 \ -v /var/run/docker.sock:/var/run/docker.sock \ -v /opt/traefik/acme.json:/acme.json \ -l "traefik.enable=true" \ -l "traefik.http.routers.traefik.rule=Host(\"traefik.domain.com\")" \ -l "traefik.http.routers.traefik.entrypoints=websecure" \ -l "traefik.http.routers.traefik.tls.certresolver=myresolver" \ -l "traefik.http.routers.traefik.middlewares=auth,redirect" \ -l "traefik.http.middlewares.auth.basicauth.users=admin:$apr1$T1Xpq5XX$4AogYQokV4FbJLKOKwCBl0" \ -l "traefik.http.middlewares.redirect.redirectscheme.scheme=https" \ -l "traefik.http.middlewares.redirect-to-https.redirectscheme.scheme=https" \ … -
how do I response partial html with fetch
I response posts in partials html with fetch, but each time get posts from server also return current page header. i just want to get header first. partial html(server responses it when requested with fetch) {% for post in posts %} <div class="posts-item"> {{post.description|linebreaks|truncatewords:20}} Published at {{post.created}} by {{post.author}} <br> {% for tag in post.tag.all %} <a href="{% url 'social:post_list_by_tag' tag.slug %}">{{tag.name}}</a> {% if forloop.last %}, {% endif %} {% endfor %} <a href="{% url 'social:post_detail' post.pk %}">post details</a> <hr><br> </div> {% endfor %} current page(posts-list.html) {% extends 'parent/base.html' %} {% block title%} posts list {% endblock %} {% block content %} <div class="posts"> {% for post in posts %} {{post.description|linebreaks|truncatewords:20}} Published at {{post.created}} by {{post.author}} <br> {% for tag in post.tag.all %} <a href="{% url 'social:post_list_by_tag' tag.slug %}">{{tag.name}}</a> {% if forloop.last %}, {% endif %} {% endfor %} <a href="{% url 'social:post_detail' post.pk %}">post details</a> <hr><br> {% endfor %} </div> <button class="load-more">load more</button> <script> var page = 2; function loadMore(){ var url = '{% if tag_slug %}{% url "post_list_by_tag" tag.slug %}{% else %}{% url "social:post_list" %}{% endif %}'+'?page='+page; fetch(url, { method: 'GET', headers: { 'content-type': 'text/html', 'x-requested-with': 'XMLHttpRequest' }, }).then(function(response){ return response.text(); }).then(function(html){ document.querySelector(".post").insertAdjacentHTML("beforeend",html); page++; }) } var btnLoadMore … -
I can't load my CSS login page in Django admin
I have a Django project that I deployed without really adding any styling for 2 reasons: I didn't know any front-end back then. I wanted to do it for the sake of doing it. Now, I have written HTML and CSS for the login page. The first place I want to apply it is the admin page, but this is what I see (as shown in the picture I shared). I can't find the problem in my project. I also uploaded the project to GitHub here: https://github.com/manirng/sukablyat-django Please ignore the name; I never thought it would go online. @import url('https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;1,300&display=swap'); *{ margin: 0px; padding: 0px; font-family: 'Poppins',sans-serif; } #bg-video{ width: 100%; height: 100vh; position: absolute; object-fit: cover; } section{ display: flex; justify-content: center; align-items: center; min-height: 100vh; width: 100%; background-position: center; background-size: cover; } .box{ position: relative; width: 400px; height: 450px; display: flex; justify-content: center; align-items: center; border: 2px solid white; border-radius: 20px; } h2{ font-size: 2em; color: white; text-align: center; } .input-field{ position: relative; margin: 20px 0; width: 310px; border-bottom: 2px solid white; } .input-field label{ position: absolute; top: 50%; left: 5px; transform: translate(-50); color: white; font-size: 1em; pointer-events: none; transition: .5s; } input:focus ~label, input:valid ~label{ top: -5px; … -
Django: Separate session expiry times for "normal" website and admin area
It would be nice if there were an easy way to define separate session expiry time for the admin area of a django website. So, admin users could log themselves into the "normal" website (seen by all users) but when they try to access the admin area for the first time, they get prompted again to enter their password. They could then do their work in the admin area and continue browsing the website for a few hours, all without entering their password again. The next day, they continue browsing the website, but upon returning to the admin area, need to input their password again. Is there a well-established pattern for this? Or a plugin that implements it? -
unable to make changes on DB or admin after crud operation./formset
I am building a mid-level project called School-Admin Panel with Django. I have completed most of the segments sucessfully, but I am having an issue with the performance forest. The formset loads and displays correctly in the browser, but after I click submit, no changes are made in the DB nothing updates on the admin side. Please help me. I am sharing portions of my code below: forms.py class PerformanceForm(forms.ModelForm): class Meta: model = Performance fields = ["student", "course", "marks", "grade"] widgets = { 'student': forms.HiddenInput(), 'course': forms.HiddenInput(), } PerformanceFormSet = modelformset_factory( Performance, form=PerformanceForm, extra=0, # only existing performances can_delete=False ) views.py def edit_performance(request): queryset = Performance.objects.all() # optionally filter by course if request.method == "POST": formset = PerformanceFormSet(request.POST, queryset=queryset) if formset.is_valid(): formset.save() return redirect("edit_performance") else: # Print errors for debugging print(formset.errors) else: formset = PerformanceFormSet(queryset=queryset) return render(request, "students/performance_edit.html", {"formset": formset}) template (performance_edit.html) <h1>Edit Performance</h1> <form method="POST"> {% csrf_token %} {{ formset.management_form }} <table border="1" cellpadding="5"> <thead> <tr> <th>Student</th> <th>Course</th> <th>Marks</th> <th>Grade</th> </tr> </thead> <tbody> {% for form in formset %} <tr> <!-- Display student/course names --> <td>{{ form.instance.student.name }}</td> <td>{{ form.instance.course.name }}</td> <!-- Editable fields --> <td>{{ form.marks }}</td> <td>{{ form.grade }}</td> <!-- Hidden inputs --> {{ form.student }} … -
Django Strategies for processing large datasets from an external API without a local replica table
I am building an SMS gateway system in Django that acts as an interface between university data sources (e.g., student information systems) and an SMS provider. The Architecture: To ensure data freshness and avoid redundancy, we decided not to maintain a local Recipient table (mirroring the external database). Instead, we use a Stateless/Proxy architecture: User selects filters (e.g., "Faculty: Engineering") in the frontend. Backend fetches the student list in real-time from the external API. We iterate through the results and create a "Snapshot" log (SmsDispatch model) for history/reporting. We send the SMS. The Problem: The external API might return large datasets (e.g., 20,000+ students). I am concerned about: Memory (OOM): Loading 20k objects into a Python list before saving to the DB. Timeouts: The external API being slow, causing the HTTP request or the Celery task to hang. The AI suggested Approach: plan to use Celery with Python Generators and Django's bulk_create to stream data and write in batches. My Question is: Is the chose of not saving the data local a good way? Is this "Generator + Batch Insert" pattern the standard way to handle this in Django/Celery to prevent OOM errors? How should I handle Partial Failures? If … -
inject an image with the other info in the response body in djangorestframework
hy i really need to send an image within the Response object of the djangorestframework endpoint . if there is anyone know how please take a moment and send a comment. Take into consideration not just the image will be sent there is some other info must be sent in the response body -
Displaying related items in an inline formset in Django
I have an inline formset in Django. I have a table called SubItem which is related to Item. Many SubItems to one Item. Some Items don't have any SubItems. Sections of code are obviously missing from below. The issue I am having is the sub items are not being displayed in the template. They don't seem to be bolting on to the main item in the inline formset using the item.subItems code. How do I display related fields like this in an inline formset? I don't need to be able to edit the sub items. view.py accountQuantityForm = AccountQuantityFormSet(instance=account) # Get items linked to an Account instance items = Item.objects.filter(accountquantity__account=account).distinct() for item in items: subItems = SubItem.objects.filter(item=item) # Add the sub items to the item object for display # item.subItems doesn't exist yet, we are creating it and adding the queryset of subItems to it. item.subItems = subItems # apply the filtered items queryset for display in accountQuantityForm for form in accountQuantityForm.forms: form.fields['item'].queryset = items context = { 'accountQuantityForm':accountQuantityForm, } template.html {% for form in accountQuantityForm %} Display form items here {% if form.instance.item.subItems.exists %} {{form.instance.item.subItems}} This is where I would insert the sub items below the main item in … -
How do I make reusable HTML elements in a Django project?
I'm new to Django, and I'm working on a project where I'm reusing static pages and changing them to be suitable Django templates. As a part of the previous project, I made some custom HTML elements using JavaScript files and customElements.define() since I'm not familiar with React. I realized that Django's templates can't modify the static JS files where these elements live, and in particular links can't be modified. The main element that I really want to be able to port over to this project is a navigation bar at the top of the screen that has a link to the homepage, and, depending on whether the user is logged in or not, will either show "login" + "register" buttons, or a notification icon and profile picture. I don't really know what the best way to do this is, I've seen some suggestions where I turn the navbar element into a templatetag, and some others are just placing the raw HTML into a file and including that inside the templates. This is the current code that I have for my navbar: /** * The main navigation bar that should only present one time in each page * of the website. … -
i need help get expirience [closed]
I learned python, django, computer science etc. to create web-sites. My level is really not good yet. I can barely create web-sites with gemini's help. Could anyone give me tips on how to get jobs, even low paid, to get some more expirience? I would prefer remote jobs. Possibly starting from a low level and gradually getting more difficult with repeated tasks. here is my github. and project link. github: https://github.com/daniel4191 project: 15.165.239.111 Thank you for watched my post. I really want better then past and want to really good expert -
Django channels tutorial issue
As I am following the Django channels tutorial (here is the link: https://channels.readthedocs.io/en/latest/tutorial/part_2.html ), I won't post any code except the specific problem I am having. In my code for the chat/routing.py, I have: from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer.as_asgi()), ] which seems to be identical to that which is given in the tutorial. Trying both single and double quotes, I get the error: SyntaxWarning: invalid escape sequence '\w' r"ws/chat/(?P<room_name>\w+)/$", consumers.ChatConsumer.as_asgi() Everything I can find says one is supposed to pre-pend the r to make the expression a regular expression, but clearly I have done so to no effect. What am I doing wrong? Have I missed something? I have copied the line from the tutorial and compared it to mine and it is identical. Thanks in advance.