Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When creating a html table in django, the layout of the data is incorrect
I wanna make a table like this image but i have a few problem. Problem 1: When you look at white background you will see 1,2,3,4 numbers. 1 and 2 same and 3 and 4 same. I don't want twice of each symptom. I want unique symptoms in the first column. Problem 2: Same problem like problem 1. Remedy names must be unique. And i made red arrows near the points. I want only one remedy_name and all points must be under the remedy_name. And here is my codes... from django.db import models from django.utils import timezone from django.contrib.auth.models import User class UserSymptom(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) symptom = models.ForeignKey(Symptom, on_delete=models.CASCADE) date = models.DateField(default=timezone.now) time = models.TimeField(default=timezone.now) def __str__(self): return f"{self.user} - {self.symptom.name} - {self.date} {self.time}" class RemedyRubrics(models.Model): remedy_name = models.ForeignKey(RemedyName, on_delete=models.CASCADE) rubric = models.TextField() point = models.IntegerField() def __str__(self): return f"{self.remedy_name.remedi_adi} - {self.rubric} - {self.point} " class Meta: verbose_name_plural = 'Remedy Rubrics' views code def homeopati4(request): user_symptoms = UserSymptom.objects.filter(user=request.user) matching_remedies = [] for symptom in user_symptoms: # Semptom adındaki ilk harfi kontrol et first_letter = symptom.symptom.name[0] if first_letter.lower() in ['ö', 'ü', 'ş', 'ı']: # Semptom adı Türkçe karakterle başlıyorsa, ilk harfi atla ve kalan kısmı içeren rubrikleri bul symptom_name_without_first_letter … -
How can I check payment status automatically?
I’m sending post requests to create a payment, then after a little time I send get request to check payment status. I don’t it’s correct or no. I’m finding a decision to automatize it. Is any ways to solve it? -
How can I display "Recent actions" in my project [duplicate]
How can I display "Recent actions" in my project for a specific application like the one in Django Panel For example, when adding a new product, deleting a product, or modifying a product Is there a library to add this feature? -
problem with gunicorn [ERROR] Exception in worker process
A month ago I rented a Shared line cloud server on Selectel and uploaded a project there, but literally a couple of days later this error appeared (see file). Since I was unable to resolve the error, I had to reset the server and start the site again. And again, not even a day had passed before the same error appeared. Feb 14 09:19:21 it-want systemd[1]: Started gunicorn daemon. Feb 14 09:19:21 it-want gunicorn[565]: [2024-02-14 09:19:21 +0000] [565] [INFO] Starting gunicorn 21.2.0 Feb 14 09:19:21 it-want gunicorn[565]: [2024-02-14 09:19:21 +0000] [565] [INFO] Listening at: unix:/run/gunicorn.sock (565) Feb 14 09:19:21 it-want gunicorn[565]: [2024-02-14 09:19:21 +0000] [565] [INFO] Using worker: sync Feb 14 09:19:21 it-want gunicorn[566]: [2024-02-14 09:19:21 +0000] [566] [INFO] Booting worker with pid: 566 Feb 14 09:19:21 it-want gunicorn[567]: [2024-02-14 09:19:21 +0000] [567] [INFO] Booting worker with pid: 567 Feb 14 09:19:21 it-want gunicorn[568]: [2024-02-14 09:19:21 +0000] [568] [INFO] Booting worker with pid: 568 Feb 14 09:19:22 it-want gunicorn[568]: [2024-02-14 09:19:22 +0000] [568] [ERROR] Exception in worker process Feb 14 09:19:22 it-want gunicorn[568]: Traceback (most recent call last): Feb 14 09:19:22 it-want gunicorn[568]: File "/home/itwant/itwant/venv/lib/python3.9/site-packages/gunicorn/arbiter.py", line 609, in spawn_worker Feb 14 09:19:22 it-want gunicorn[568]: worker.init_process() Feb 14 09:19:22 it-want gunicorn[568]: … -
django reports invalid form with request method POST
I render the html when login url is hit and then invoke another url to handle submitted form. Following is the method that processes the form - def process_loginform(request): print(request.method) form = LoginForm(request.POST) if form.is_valid(): print("Valid form") else: print("Invalid form") return HttpResponseRedirect("/login/welcome/") The Login form html - {% extends 'base.html' %} {% block content %} Hello <form action="/login/process_loginform/" method="post"> {% csrf_token %} <label for="username">Username</label> <input id="username-val" type="text" name="username-name" /> <label for="password">Password</label> <input id="password-val" type="password" name="password-name" /> <input type="submit" value="Login" /> </form> {% endblock %} forms.py - from django import forms class LoginForm(forms.Form): username = forms.CharField(label="username", max_length=64) password = forms.CharField(label="username", max_length=64) Console output - (ubuntu-7Wf190Ea) ubuntu@ip-172-31-4-242:~/ka$ ./manage.py runserver 0.0.0.0:1890 Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). February 14, 2024 - 10:28:18 Django version 4.2.10, using settings 'ibs.settings' Starting development server at http://0.0.0.0:1890/ Quit the server with CONTROL-C. [14/Feb/2024 10:28:23] "GET /login/ HTTP/1.1" 200 729 request: <WSGIRequest: POST '/login/process_loginform/'> POST **Invalid form** I'm following this documentation - https://docs.djangoproject.com/en/5.0/topics/forms/ Why is the form invalid ? I tried to google the error, no luck. I was expecting to understand why is my login handler reporting an invalid form. Thanks -
Language translator [closed]
I need to create a website in django I wanted to add a settings in that, like language translation I needed only the content has to be changed the name remains same (eg: the OnePlus node blue tide this will remains same )and this change will only effect the headers,nav etc ,I use i18 n But it doesn't give proper output I need a language translation settings only the headers footers change -
Overriding ordering of related object in queryset
I have two related models, Customer and Config. Customer is set to automatically order by order. Now I want to select the latest Config entry for each distinct set of customer and report_type. That's usually accomplished by an order_by on all the distinct fields as well as a descending ordering on the date, followed by a distinct on the distinct fields. However, since Django sneaks in another ORDER BY on Customer.order in the eventual query, DISTINCT says its arguments don't match those of ORDER BY. I'd like to override the ordering on Customer in this case. class Customer(models.Model): name = models.TextField() order = models.IntegerField() class Meta: ordering = ["order"] class Config: customer = models.ForeignKeyField(Customer) created = models.DatetimeField() report_type = models.TextField() cfgs = ( Report.objects .filter() .order_by("customer", "report_type", "-created") .distinct("customer", "report_type") ) There is a solution, albeit one I feel is a little bit hacky. By doing the order_by and distinct calls on the customer_id field, it won't try to LEFT JOIN Customer and also forego its ordering. The problem here is that that means I'll have to make another database call to fetch the Customer objects. It's not a big deal, but if I could override the ordering on Customer, … -
External trigger (PostgreSQL) for Django application
I have a difficulty with my Django application: I have two databases, and I would like that when an instance is added to PostgreSQL, a Django function is triggered to work on the default database. Could you list the steps to follow? Thank you. I have created a trigger in the external database, but I can't get Django to react despite implementing pgtrigger. -
Can we avoid using django session to work with request body params data?
I have two django restframework classes(POST and GET)respectively, as seen below class demo(CreateAPIView): serializer_class = DummySerializer def post(self, request, *args, **kwargs): ID = request.data.get("ID") org = request.data.get("org") ent= request.data.get("ent") request.session['ID '] = ID request.session['org'] = org request.session['ent'] = ent request.session.save() class demo1(ListAPIView): serializer_class = MySerializer def get_queryset(self): ID = request.session.get("ID") org = request.session.get("org") ent= request.session.get("ent") I have two queries: My aim is to fetch those 3 params from request body in demo class and add it to a session and then use the values in demo1 class for further data manipulation. So, I migrated the default django in-built apps in the development sqlite DB and I could see the flow of the data from demo class to demo1 class. But in my actual working environment, I am trying to avoid the session migrations until I don't have any further options. In a new django app which I have created in my working environment, in the models.py I have define the structure of an existing table from my MySQL db. Hence, if I do a migrations and then mnigrate, will the migrations going to make any further changes in the MYSQL tables, or it will only compare the existing schema and … -
Document repository and search using Generative AI and Django
I am not sure, this is right forum to get help here. But, need some expert help on this. I have created a chatbox using Javascript, Django framework and AI. If user asks any question from chatbox, then model will help to answer with defined responses. Now, I would like to extend my application to create document repository for any category type using generate AI LLM's and AI. My new requirement: If user request any specific document version using chatbox, then model should respond with that specific document link which was defined in server with view/download option. Also, user want specific data from specific document version using Gen AI then model should respond. Can someone let me know, how I can achieve this using Gen AI and Django ? Is this possible? If yes, Any reference link/ which API's which help for my requirement ? -
Desktop App with Django, DRF, Vue 3 JS, Electron JS and Forge Electron - links out of the package error on make
What I am trying to do: Build and package a very simple desktop app using: Python Django as a backend (with Django Rest Framework for a rest api) Vue 3 js for the frontend (using Axios to consume the API) Electron JS to make it a desktop app and Forge Electron to package it. I am using a virtual env for the Django app (pyenv). The build and run works perfectly: the app just fetch a list of posts from Django using DRF endpoints and a GET request from the Vue App. The issue is when I want to make a package and deploy it. Forge Electron comes with an error: An unhandled rejection has occurred inside Forge:links out of the package. And more specifically: An unhandled rejection has occurred inside Forge: Error: /var/folders/3v/kk4yh47x7hlgs8rv94dxnx700000gn/T/electron-packager/tmp-2YhdSt/Electron.app/Contents/Resources/app/python/.venv/bin/python: file "../../../../../../../../../../../../Users/macbookpro/.pyenv/versions/3.10.4/bin/python3.10" links out of the package I have tried multiple things I have found browsing: set asar:false --> it complains that it needs to be true or an object see if the issue was linked to node.js libs --> I found something about node-gyp bit it seems not relating to the issue. The issue seems to be linked to where Python is located... If that … -
In Django python, Logout from the site cannot insert data into mysql by only presss the logout button
There is the site that has logout button. I can insert data into mysql database in login. However, press the logout button did not insert data into mysql. I want to try is it possible to insert data into mysql simply by pressing the button. -
How to Use React to Authenticate to Django REST Framework
I am trying to figure out how to authenticate to the Django REST Framework with React. I am using AXIOS. But no matter what I try, I seem to get a 403 - CSRF verification failed. Request aborted. In Chrome, I go to DRF's default login point. I enter the username and password and click submit. It works in Chrome. In DevTools, I can see the POST. Now if I try that same POST in React, I get a 403 with the CSRF error. How is that even possible? In React I am doing the same thing that Chrome is doing. How can it produce a different result? Here's me logging in from Chrome... enter image description here What am I missing? What am I missing? I keep reading about doing a GET request, looking at the set-cookie csrf token and value, and putting that in a header on my POST request. I've tried that and every variation I can think of to no avail. -
What are the best practices or recommendations that will make it easier to access related models in django?
class Customer(models.Model): user = ForeignKey(User, on_delete=models.CASCADE) ... class Organization(models.Model): usercustomer = models.ForeignKey(Customer, on_delete=models.CASCADE) ... In the template, to get the user name, I write {{ organization.customer.user.first_name }} how can I shorten it? class Organization(models.Model): usercustomer = models.ForeignKey(Customer, on_delete=models.CASCADE) ... def get_user_first_name(self): return self.usercustomer ].user.first_name I wanted to solve this by writing methods in the model, but it's not so convenient, I want to find a more flexible solution -
Displaying Data from Database (Django) [closed]
I'm a beginner. Using Django for the first time. I'm building a website for pet adoption. Currently working on the database UI. I want the database to be displayed somewhat like this... example UI or something like petfinder -> example UI Basically, when someone comes to look for all the available pets for adoption, I want them to be displayed as single objects...would django_tables2 be the right fit for this? It's not exactly a table so I don't know if I should be using django_tables2 for this. Are there other ways to achieve this kind of UI for displaying data? Haven't really tried anything except django_tables2 and it's displaying everything in a table format as expected but that's not really what I want. -
Install Google Font Family with Docker on Linux
I want to download and install a single google font family with Docker. I found this and it works, but i don't ALL the fonts. Just one family. RUN wget https://github.com/google/fonts/archive/main.tar.gz -O gf.tar.gz RUN tar -xf gf.tar.gz RUN mkdir -p /usr/share/fonts/truetype/google-fonts RUN find $PWD/fonts-main/ -name "*.ttf" -exec install -m644 {} /usr/share/fonts/truetype/google-fonts/ \; || return 1 RUN rm -f gf.tar.gz RUN fc-cache -f && rm -rf /var/cache/* this seems to work to download. RUN wget -qO- https://fonts.googleapis.com/css2?family=Fira+Sans so how do I stick the font family download here? RUN mkdir -p /usr/share/fonts/truetype/ Linux is not my thing so your help is very appreciated. Thank you. -
Error with testing a dynamic url in django
url test passes with reverse function but fails with raw url This is the test from django.test import TestCase from django.urls import reverse from django.contrib.auth import get_user_model from .models import Post # Create your tests here. class BlogTests(TestCase): def setUp(self): self.user = get_user_model().objects.create_user( username="testuser", email="test@email.com", password="secret" ) self.post = Post.objects.create( title="A good title", author=self.user, body="Nice body content" ) def test_post_detail_view(self): #response = self.client.get(reverse("post_detail", args=[self.post.pk])) #no_response = self.client.get(reverse("post_detail", args=[10000])) response = self.client.get(f"/post/{self.post.pk}/") no_response = self.client.get("/post/1000/") self.assertEqual(response.status_code, 200) self.assertEqual(no_response.status_code, 404) self.assertContains(response, "A good title") self.assertTemplateUsed("post_detail.html") this is the view from django.views.generic import ListView, DetailView from .models import Post # Create your views here. class BlogListView(ListView): model = Post template_name = "home.html" class BlogDetailView(DetailView): model = Post template_name = "post_detail.html" this is the url configuration from django.urls import path from .views import BlogListView, BlogDetailView urlpatterns = [ path("", BlogListView.as_view(), name="home"), path("posts/<int:pk>", BlogDetailView.as_view(), name="post_detail"), ] the commented out lines work in the test but the uncommented ones return 404 #response = self.client.get(reverse("post_detail", args=[self.post.pk])) #no_response = self.client.get(reverse("post_detail", args=[10000])) response = self.client.get(f"/post/{self.post.pk}/") no_response = self.client.get("/post/1000/") Please explain I tried the reverse urls which works but still don't understand why the raw urls don't work. -
Collecting and Returning Error List in Django Rest Framework
I need to gather a list of errors in Django Rest Framework and return them to the frontend without performing any database or media operations. For example, errors during serialization, billing validation (if the user lacks permissions), or if a user tries to create something with a name that already exists. I want all validations to pass and then return this list to the user. I'm interested in potential approaches or if anyone has encountered a similar issue -
Hello, I want to create model inferencing webapp using django and react. like object detection but all will be done in a webpage. Any ideas please
Basically, we already have some ml models like object detection. But we need to make that models run in react-django webapp. Please let me know where to start. Currently, What I did is streamlit. but I need to know if ots possible to run models in a webapp..like hugging face. -
The view account.views.login_view didn't return an HttpResponse object. It returned None instead
User is trying to Register or Login. Register is working fine. Login login shows error. Login page not loading. Here is my code: from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate, logout from account.forms import RegistrationForm, AccountAuthenticationForm def registration_view(request): context= {} if request.POST: form = RegistrationForm(request.POST) if form.is_valid(): form.save() email = form.cleaned_data.get('email') raw_password = form.cleaned_data.get('password1') account = authenticate(email=email, password=raw_password) login(request, account) return redirect('home') else: context['registration_form'] = form else: #GET request form = RegistrationForm() context['registration_form'] = form return render(request, 'account/register.html', context) def logout_view(request): logout(request) return redirect('home') def login_view(request): context = {} user = request.user if user.is_authenticated: return redirect("home") if request.POST: form = AccountAuthenticationForm(request.POST) if form.is_valid(): email = request.POST['email'] password = request.POST['password'] user = authenticate(email=email, password=password) if user: login(request, user) return redirect("home") else: form = AccountAuthenticationForm() context['login_form'] = form return render(request, 'account/login.html', context) type here When on Click event occur on the Login button. Login page should be displayed. It is showing Error. Python Version: v2024.0.1 -
DEBUG=False is not showing static and media files in Django project on Cpanel
I've looked into many articles and videos on this topic, but either I didn't understand or the solutions were insufficient. I would be very happy if you could help. I developed a Django project and deployed it on cPanel. My static and media files don't work when DEBUG = False. What should I do to make it work properly on cPanel? I'm not sure if Whitenoise is being used during the deployment phase. How can I run my Django project on cPanel in a suitable and fully functional manner? Here are my current codes: Settings.py: DEBUG = True ALLOWED_HOSTS = ['*'] STATIC_URL = '/static/' STATIC_ROOT = '/home/ayvacioglu/ayvacioglu_v2/static/' # STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] MEDIA_URL = '/media/' MEDIA_ROOT = '/home/ayvacioglu/ayvacioglu_v2/media/' Urls.py: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('pages.urls')), path('', include('portfolio.urls')), path('', include('services.urls')), path('', include('blog.urls')), ] + static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) If you need any other info i can provide it. Thank you so much -
Why is key name undefined when trying to display key value in html?
I'm trying to display database data in html using Javascript fetch api. I have looked at plenty of content for this problem but nothing seems to work right. However, I can display all the data in json format no problem. The problem occurs when I reference my model field names (key names) in javascript. sun_from_hour returns undefined. Is it a notation problem? I have tried several solutions. class SundayTime(models.Model): sun_teacher_id_time = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True, default='', related_name='sun_teacher_time_available_id') sun_from_hour = models.TimeField(null=True, blank=False) sun_to_hour = models.TimeField(null=True, blank=False) class SunJsonListView(View): def get(self, *args, **kwargs): times = list(SundayTime.objects.values('sun_from_hour', 'sun_to_hour')) return JsonResponse({'times': times}, safe=False) const sunButton = document.getElementById('sun_availability_show'); const sunContainer = document.getElementById('sun_availability_div'); const sunUrl = '/daily_appointment_availability-sun_json/' sunButton.addEventListener('click', reqSunData); function reqSunData() { fetch(sunUrl, { method: "GET", }) .then((response) => { return response.json(); }) .then(times => sunAdder(times)) .catch((error) => { console.error(error); }) } function sunAdder(times) { console.log(times); const ul = document.createElement('ul'); sunContainer.append(ul); Object.keys(times).forEach(timeData => { console.log(Object.values(times)); const li = document.createElement('li'); li.insertAdjacentHTML('beforeend', `<li>[${times.sun_from_hour}]</li>`); // here sun_from_hour is undefined li.textContent = JSON.stringify(times); ul.append(li); }) } // the json data that is displayed in html // {"times":[{"sun_from_hour":"00:00:00","sun_to_hour":"00:45:00"}, // {"sun_from_hour":"01:30:00","sun_to_hour":"01:45:00"}]} -
Problem loading wasm data for SciChart in Django - scichart2d.data = 404
I can only load a blank SciChart surface with a "loading... spinner". Firefox console says: Uncaught Error: Internal Server Error : http://127.0.0.1:8000/charts/scichart/scichart2d.data Django is serving scichart2d.wasm correctly, but not scichart2d.data (which is in the same static dir) My HTML and javascript seem to be working, the Webpack bundle loads and logs to console. I followed the SciChart tutorial here. I don't know where this problem is coming from. Is it Webpack, Django, or SciChart? Here's the Django terminal output: System check identified no issues (0 silenced). February 14, 2024 - 01:14:59 Django version 5.0.2, using settings 'core.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [14/Feb/2024 01:15:03] "GET /charts/scichart/ HTTP/1.1" 200 7752 [14/Feb/2024 01:15:03] "GET /static/bundle.js HTTP/1.1" 200 5155989 [14/Feb/2024 01:15:03] "GET /static/js/bootstrap.bundle.min.js.map HTTP/1.1" 304 0 Not Found: /charts/scichart/scichart2d.data [14/Feb/2024 01:15:04] "GET /charts/scichart/scichart2d.data HTTP/1.1" 404 3985 [14/Feb/2024 01:15:04] "GET /static/scichart2d.wasm HTTP/1.1" 304 0 I tried intercepting the request for '/charts/scichart/scichart2d.data' in Django: charts/urls.py from .views import scichart, sciChartData, urlpatterns = [ path("scichart/", scichart, name="scichart"), path('scichart/scichart2d.data', sciChartData, name="sciChartData") ] charts/views.py def sciChartData(request): print(request) dataURL = static('scichart2d.data') return FileResponse(open(dataURL,'rb'), filename='scichart2d.data', as_attachment=True, ) but I couldn't successfully return the .data file to SciChart. The print(request) is <WSGIRequest: GET '/charts/scichart/scichart2d.data'> Python Version … -
Django: Migrating from multiple databases to a single database?
I'm relatively new to Django (and web systems architecture more broadly) and mistakenly thought that building my project with separate databases for user data and core application data was a good idea. I originally created two applications, core and users, with separate router classes: settings.py DATABASES = { "default": { }, USERS_DATABASE: { "ENGINE": "django.db.backends.postgresql", "NAME": "postgres", "USER": ..., "PASSWORD": ..., "HOST": "127.0.0.1", "PORT": "5000", }, CORE_DATABASE: { "ENGINE": "django.db.backends.postgresql", "NAME": "postgres", "USER": ..., "PASSWORD": ..., "HOST": "127.0.0.1", "PORT": "5000", }, } routers.py class AuthRouter: route_app_labels = { "auth", "contenttypes", "sessions", "admin", } ... class CoreRouter: route_app_labels = { "core", } ... Knowing now that it's not necessary for our project to use separate core and users databases (and that doing so will give us more problems in the future), I'd like to migrate the users database into the core database and assign the core database to be the default. There are only two users at the moment, so I'm fine with losing the users data and recreating the superuser if need be. However, migrating the users database doesn't seem as straightforward as editing settings.py and creating migrations. Editing the databases settings.py to both point to the core database and … -
how to collect information of this json file through django?
so, I'm creating a django weather app project. My idea is: The user input the name of a city The city need to be in my database If it is, so the weather api will receive the city coordinates and output data I would like to know how do I get parameters of a json file through django. Do I need to do it with the views? create a model? some request? I did this in views: from django.http import HttpResponse import requests from datetime import datetime from zoneinfo import ZoneInfo def weatherdata(request): response = requests.get('api is here').json() context = {'response':response} return render(request,'home.html',context) def citynamesinfo(request): response = request.FILES() #I don't what to do here # input localization # recognize specific coordenates and in models: from django.db import models # Create your models here. class Weather(models.Model): city = models.CharField(max_length=100) temperature = models.DecimalField(max_digits=5,decimal_places=2) condition = models.CharField(max_length=100) precipitation = models.CharField(max_length=100, null=True) humidity = models.DecimalField(max_digits=5,decimal_places=2) considering the json file is like this: [{"geoname_id": "3112344", "name": "R\u00e1fales", "ascii_name": "Rafales", "alternate_names": ["Rafales", "Rafels", "R\u00e1fales", "R\u00e1fels"], "feature_class": "P", "feature_code": "PPLA3", "country_code": "ES", "cou_name_en": "Spain", "country_code_2": null, "admin1_code": "52", "admin2_code": "TE", "admin3_code": "44194", "admin4_code": null, "population": 175, "elevation": null, "dem": 634, "timezone": "Europe/Madrid", "modification_date": "2012-03-04", "label_en": "Spain", "coordinates": …