Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reference Serializer fields from Model in Django Rest Framework
The usual way of creating ModelSerializer in Django Rest Framework is specifying the fields attribute: class MyModelSerializer(serializer.ModelSerializer): class Meta: model = ModelConfig fields = ( 'id', 'uid', 'hashid', 'created_at', 'updated_at', 'added_by', 'updated_by', 'qr_code',) However in bigger projects, refactoring can be easier if the fields can be referenced through their Model, instead of specifying them as a string literal. However I don't know how this could be done in the most OOP way. I have tried using Model._meta.get_field(field) but this also only accepts the field_name, not a reference to the attribute. Something like Model.field.name would be great. Is this somehow possible? -
JavaScript returns value on the first review only, l don't know why
Am having a problem but l nor know what brings it. When I try to loop the Django to for JavaScript to display the Stars, it returns only on the first review and the rest it returns nothing. Now what can't do so that each user who adds a rating it displays it's stars not displaying only the first one? Below it's my HTML and JavaScript below Even l added also an image for results if try to reflesh the page. Html {% for review in reviews %} <p>display of numbers </p> <option value="{{ review.rating }}" id="hours"></option> <div class="staz"> <p id="demo"></p> {% endfor %} JavaScript <script> let hour = document.getElementById('hours').value; let greetings; if (hour == 1){ greetings = "★"; } else if (hour == 2){ greetings = "★★" } else if(hour == 3){ greetings = "★★★" } else if(hour == 4){ greetings = "★★★★" } else if(hour == 5){ greetings = "★★★★★"; } document.getElementById('demo').innerHTML = greetings </script> Results I expected that each review, it returns it's stars. -
Django deploy never completes on render.com
I have created app on Django. It works locally. Now I am trying to deploy it on render.com. Although, build is successful deploy never completes: Apr 19 05:33:01 PM 128 static files copied to '/opt/render/project/src/myproject/staticfiles'. Apr 19 05:33:03 PM Operations to perform: Apr 19 05:33:03 PM Apply all migrations: admin, auth, avito, contenttypes, sessions Apr 19 05:33:03 PM Running migrations: Apr 19 05:33:03 PM No migrations to apply. Apr 19 05:33:04 PM ==> Uploading build... Apr 19 05:33:13 PM ==> Build uploaded in 8s Apr 19 05:33:13 PM ==> Build successful 🎉 Apr 19 05:33:13 PM ==> Deploying... Apr 19 05:33:44 PM ==> Starting service with 'cd ./myproject && gunicorn --bind 0.0.0.0:8000 --workers=2 --preload --log-level debug myproject.wsgi' Apr 19 05:33:55 PM [2023-04-19 17:33:55 +0300] [51] [INFO] Starting gunicorn 20.1.0 Apr 19 05:33:55 PM [2023-04-19 17:33:55 +0300] [51] [DEBUG] Arbiter booted Apr 19 05:33:55 PM [2023-04-19 17:33:55 +0300] [51] [INFO] Listening at: http://0.0.0.0:8000 (51) Apr 19 05:33:55 PM [2023-04-19 17:33:55 +0300] [51] [INFO] Using worker: sync Apr 19 05:33:55 PM [2023-04-19 17:33:55 +0300] [61] [INFO] Booting worker with pid: 61 Apr 19 05:33:55 PM [2023-04-19 17:33:55 +0300] [62] [INFO] Booting worker with pid: 62 Apr 19 05:33:55 PM [2023-04-19 17:33:55 +0300] … -
I cant runserver from manage.py in Django
i want to runserver from my manage.py file for my Django project but i gives me error i should say that my graphic is old(Nvidia Geforce 9500gt) and the OpenGL version its : 1.1 , i think the error is for the open gl and i need a better graphic card but see my error. My python version is : 3.8 and my django is : 4.2 and my vs code is : 1.70 July 2020 I used this code for runserver: .\manage.py runserver i should say that i cant use the python before the manage.py .manage.py runserver because my vs code is old and it gives me error! but when i use the first code this error happend in my terminal: [2612:0419/191928.798:ERROR:gl_surface_egl.cc(808)] EGL Driver message (Error) eglCreateContext: Requested GLES version (3.0) is greater than max supported (2, 0). [2612:0419/191928.798:ERROR:gl_context_egl.cc(352)] eglCreateContext failed with error EGL_SUCCESS as i say my graphic card is old. -
Getting error while install django-autofixture
[getting error while installing django-fixture, tried pip install django-fixture, tried pip3, tried specific version of autofixture still getting error "AttributeError: 'UltraMagicString' object has no attribute 'endswith' [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output." ](https://i.stack.imgur.com/RHxRR.png) -
Error while deploying Django with mod_wsgi
I'm trying to deploy my django project with mod_wsgi. My site config: <VirtualHost *:80> ServerName djangoproject.com ServerAlias www.djangoproject.com DocumentRoot /home/djangoproject ErrorLog /home/djangoproject/logs/back-error.log CustomLog /home/djangoproject/logs/back-access.log combined <Directory /home/djangoproject/djangoproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess djangoproject.com python-path=/home/djangoproject/ python-home=/home/djangoproject/venv WSGIProcessGroup djangoproject.com WSGIScriptAlias / /home/djangoproject/djangoproject/wsgi.py </VirtualHost> But im getting error ModuleNotFoundError: No module named 'django' My project structure: /home/djangoproject /djangoproject ... wsgi.py /venv /logs manage.py What am i doing wrong? -
Django: How can I use subquery and annotate with 2 tables in 2 different databases in Django?
I have Table 1 in database1 and Table2 in database2. I try to use annotate and subquery like bellow but it's not work. from django.db.models import Subquery, OuterRef, Count from app1.models import Table1 from app2.models import Table2 subquery = Table2.objects.filter(table1_id=OuterRef('id')).values('table1_id').annotate(count=Count('id')).values('count') queryset = Table1.objects.annotate(table2_count=Subquery(subquery, output_field=models.IntegerField()), using='database1') The error is: QuerySet.annotate() received non-expression(s): database1. -
Generate a PDF with FPDF with content from django-website
I'm trying to run a Python code that are using the FPDF- library to produce a pdf with some simple text. def example(request): .... generatePDF(parameter1, parameter2, parameter3) ... return HttpResponse("PDF generated") def generatePDF(x,y,z): import fpdf from FPDF pdf = FPDF pdf = FPDF('L", "mm", "A4") pdf.addpage() ... ... ... pdf.output("test.pdf", "F") The Django-code without do run perfectly smoothly itself, and the function for PDF- production runs without problem when I call it in the terminal. But when I try to use the PDF function inside a Django view, I only get an Error 500 in return. Why is this happening? -
How to show __str__ representations for existing Inline objects in the admin UI, but still use the form for adding new objects
I have a Django Admin view with a number of inlines. The 'Add another ' works as expected and brings up an empty form to fill in the values. Once added though, it shows that related object in form view, and all fields on all inlines remain editable. What I'd like to achieve is that all existing objects are listed in their __str__ representation, but the 'Add another' button still brings up the form. Can this be done in Django Admin, or am I looking for too much? -
Keep on getting this error message when trying to run my django server: [Errno 2] No such file or directory
I'm trying to run my django server but keep on getting this error, [Errno 2] No such file or directory. I tried using the cd manage.py command but also got this error cd : Cannot find path 'C:\Users\nyaknoiton\Desktop\Django 2\manage.py' because it does not exist. -
Django model for ordered list with polymorphic relations
I am trying to figure out the way to implement a Django model for optical/mechanical simulations for photovoltaic modules and glazing units. The simplest real-life representation of the problem looks like this: Position Material 1 Glass 2 EVA foil 3 Solar cells 4 EVA foil 5 PVF Here is my idea of the data representation: The class PVmodule class handles has the ForeignKey field referencing its composition like so: class PVmodule(models.Model): #---components---# composition = models.ForeignKey(ModuleComposition,related_name="composition",on_delete=models.CASCADE) The class ModuleComposition is an abstraction of an optical stack (as in the table above) - set of ordered materials like glass, gas, coatings and polymers... each represented by separate django model. Upon save() it handles optical calculations based on the ManyToMany relation with the StackItem class and fills in its' remaining fields with data automatically: class ModuleComposition(models.Model): self.stack = models.ManyToManyField(StackItem) The StackItem class is a representation of a single material on a specific position. It relates via ForeignKey to a table handling the specific material parameters. class StackItem(models.Model): self.position = models.PositiveIntegerField() self.material = models.ForeignKey( ... ) I would like this allows the user to define the module composition step by step or to an already existing module composition for quick evaluation. However, I cannot … -
Automatically update and render item quantity on cart update
I have been working on my cart functionality but I cannot seem to get the cart item.quantity to automatically update without a page refresh. I'm wondering how I could modify the code below to not only update my CartIcon but update specific item quantity too or whether I need a new function/util entirely. Here is the HTML snippet with the variable {{item.quantity}} I would like to automatically update when the quantity is changed. <svg class="icon--cart change-quantity update-cart" data-product="{{item.product.id}}" data-action="add" > <use href="/media/sprite.svg#plus-solid"/> </svg> {{item.quantity}} <svg class="icon--cart change-quantity update-cart" data-product="{{item.product.id}}" data-action="remove"> <use href="/media/sprite.svg#minus-solid"/> </svg> Here is a util I made for updating the Cart Icon number in my header: @login_required def get_cart_quantity(request): cart = get_object_or_404(Cart, user=request.user) quantity = sum(item.quantity for item in cart.items.all()) return JsonResponse({'quantity': quantity}) Here is my current script that successfully updates my CartIcon: function updateCartQuantity() { fetch("/get_cart_quantity/") .then((response) => response.json()) .then((data) => { document.getElementById("cart-quantity").textContent = data.quantity; }) .catch((error) => { console.error("Error fetching cart quantity:", error); }); } // Call updateCartQuantity when the page loads and after adding an item to the cart window.addEventListener("load", updateCartQuantity); Below is the quantity field I want to automatically update, so it is specific to the item, not the whole cart quantity. -
Limit the number of objects in django TabularInline
I use Django, and I want create a TabularInline showing a maximum of 10 results You can configure it with max_num and extra, but that does not limit the results. They have a special section on "Limiting the number of editable objects". Where they say "max_num does not prevent existing objects from being displayed". But also not how its actually done. I can also not overwrite the get_queryset method because Django does a filter later and then I get TypeError: Cannot filter a query once a slice has been taken. Does anyone know how I can do this? -
Create Cart object once user logs in
My app is built so that only authenticated users can purchase items so there is only need for a cart when the use logs in, my script then pulls the cart id that relates to that user so my API can work its magic. I cannot get the Cart object to be created. I have tried many attempts and this is my latest: ef user_login(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) try: cart = Cart.objects.get(user=user) except Cart.DoesNotExist: cart = Cart.objects.create(user=user) request.session['cart_id'] = cart.id messages.success(request, ("You were successfully logged in...")) else: messages.success(request, ("There was an error logging in, please try again...")) return redirect('home') return render(request, 'authenticate/login.html', {}) -
Selecting a database to use per specific APIView in the Django application
Recently I added a second database to my Django application. I have prepared API a long time ago with the use of djangorestframework and now I would like to be able to choose which view should use which database. I tried using Database Router however, I do not think it suits my need cause many of my views use the same models. I also hope to find a more elegant solution than just adding .using() method to every single query. -
DatabaseError at /admin/core/profile/add/ No exception message supplied
I am building class models using Django and mongodb is connected to my server successfully. When I create User account as UserAdmin, I can create and save new data and everything is snyc to my database. However, when UserAdmin or superuser tried to create a Profile, which is built by using foreign key User model, I got this error. I tried to fix this error by downgrading django and djongo, but local testing worked well but server got crashed. So downgrade the package is not a solution. How can I this database error?... I've been trying to fix this for 3 days, but i still got lost and do not know which part is wrong like either my code or my db setting .... here is my model.py and admin.py code. Please lmk if u want more information.. from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import models class CustomUserManager(BaseUserManager): def create_user(self, username, email, password=None, role=None): if not username: raise ValueError('Users must have a username') if not email: raise ValueError('Users must have an email address') user = self.model( username=username, email=self.normalize_email(email), role=role ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email, password, role=None): user = self.create_user( username=username, email=email, password=password, role=role ) … -
Django Count in Annotate and Subquery are much slower than simply iterating over my items and filtering individualy
I'm trying to count how many documents per project (among other things) have been registered, Registered also holds other values like DateTime and User (just a disclosure they are unrelated to my issue). Iterating through a list and querying ~54 times ends up being much faster than Annotate or Subquery (13 vs 27 seconds) I have 4 tables which go like this Project -> Batch -> Document -> Registered. Right now we have 54 Projects, 20478 Batches, 3231095 Documents and 312498 Registered. The timings listed below are for the entire view, not just the bits represented, but you can have an idea on their impact... projects = Project.objects.filter(completion_date__isnull=True) # "Fast", takes around 13.5 seconds to evaluate for project in list(projects.values('id')): count = Document.objects.filter(batch__project_id=project['id], registered__isnull=False) # Both methods below are much slower, taking around 27 seconds to evaluate # Simple annotation projects = projects.annotate(count=Count('batches__documents', filter=Q(batches__documents__registered__isnull=False), distinct=True)) # An attempt to simulate the first list iteration query without multiple db hits, ends up exactly as slow as annotate subq_registered = Document.objects.filter(batch__project_id=OuterRef('id'), registered__isnull=False).annotate(count=Func(F('id'), function='Count')).values('count') projects = projects.annotate(count=Subquery(subq_registered)) I expected Subquery to be faster than my first method, as it would mimic it, but its just as slow as simple count + annotation. Is … -
Django Views "PageNot Found"
i have a password change page and i want to move it to another page after successfully changing my password, but my code is giving me a page "page not found" path( "passwordchange/", auth_views.PasswordChangeView.as_view( template_name="user/passwordchange.html", form_class=PasswordChangeForm, success_url="/passwordchangedone/" ), name="passwordchange", ), path( "passwordchangedone/", auth_views.PasswordChangeDoneView.as_view(template_name="user/passwordchangedone.html"), name="passwordchangedone", -
set models of a school in django
i want to create a school like tables in django: where a teacher has few classroom and a classroom has only one teacher and a student who has one classroom but a classroom has many students i build my models like this: class Classroom(models.Model): classID = models.CharField(primary_key=True,validators=[MinLengthValidator(2)], max_length=50, blank=False) class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) school_name = models.CharField(validators=[MinLengthValidator(2)], max_length=50, blank=False) city = models.CharField(validators=[MinLengthValidator(2)], max_length=50, blank=False) classroom = models.ForeignKey(Classroom) class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) fullName = models.CharField(validators=[MinLengthValidator(2)], max_length=50, blank=False) studentLevel = models.IntegerField(default=0) studentUnit = models.IntegerField(default=0) classroom = models.ForeignKey(Classroom) done = models.BooleanField(default=False) is it ok to do it like this because i get confused with the relations -
How to store temporary data in Django?
I'm creating an app on Django: it's a collaborative game with a chat. Every time you join a game, you choose a nickname, and it exists until you leave the game. Also chat: it is stored until the end of the game. What is the best way to store nicknames and chat? i'm a beginner and don't understand that really... Should i use some cookies or work with sessions? Please help me it's my university project... -
Django database update + celery recurrent task
I'm using django + celery and having some problems with concurrency. I have the following scenery: One endpoint that updates an object called Route and a celery task that runs each 5 seconds that do some actions based on that Route object data.. The problem is, sometimes the action from my endpoint happens so closely to the celery task execution that the object wasn't updated on the database yet resulting in wrong interpretation. I'm reading about atomic transactions but don't know for sure how to implement that in my case. Any suggestions? Thank you! -
How can i integrate spotify web api in my django web app to display tracks, artists and playlists
I am creating a web app for streaming and downloading music. I want to fectch tracks, albums and artists using spotify api and display them on my home page but my website keeps redirecting endlessly. please help, this is my code: import requests import spotipy.util as util import pylast import random import os def home(request): scope = 'user-library-read' # Authenticate the user token = util.prompt_for_user_token( username=None, scope=scope, client_id='beaf4d3d7ca34bceb485a30636dedcdf', client_secret=SPOTIPY_CLIENT_SECRET, redirect_uri='http://localhost:8888/home/', ) if token: sp = spotipy.Spotify(auth=token) # Get a random track track_results = sp.search(q='year:2022', type='track', limit=50, offset=0) random_track = random.choice(track_results['tracks']['items']) track_name = random_track['name'] track_artist = random_track['artists'][0]['name'] track_album = random_track['album']['name'] track_image = random_track['album']['images'][0]['url'] # Get a random album album_results = sp.search(q='year:2022', type='album', limit=50, offset=0) random_album = random.choice(album_results['albums']['items']) album_name = random_album['name'] album_artist = random_album['artists'][0]['name'] album_image = random_album['images'][0]['url'] # Get a random artist artist_results = sp.search(q='year:2022', type='artist', limit=50, offset=0) random_artist = random.choice(artist_results['artists']['items']) artist_name = random_artist['name'] artist_image = random_artist['images'][0]['url'] context = { 'track_name': track_name, 'track_artist': track_artist, 'track_album': track_album, 'track_image': track_image, 'album_name': album_name, 'album_artist': album_artist, 'album_image': album_image, 'artist_name': artist_name, 'artist_image': artist_image, } else: context = {} return render (request, 'search.html', context) #this is my urls.py: #urlpatterns = [ #path('home/', views.home, name='home'), #path('search/', views.search, name='search'), #] #but if i load the page it enters a redirect … -
JWT Token payload configuration sending more data fields than asked for?
I have to setup JWT token authentication for one of my projects. Lets call it project B which is a video conferencing project backend. The authentication needs to happen after connecting to Project A which is a Django rest api with all the users registered. My front end app will connect to Project A , get the payload and send the JWT to project B for authentication. For now project B requires only 2 data fields : "aud" : JWT_APP_ID "secret" : JWT_APP_SECRET The above 2 fields is what project B requires to authenticate and start the video conference. JWT_APP_ID & JWT_APP_SECRET are both entered on project A end and fetched by the front end app. However, at the risk of sounding stupid, can we send more than 2 fields i.e. more than what is asked for by project B? I have some important fields like call_duration, call_type(audio/video) which needs to be sent. Hopefully I will be able to send the data back through an event synch module plugin on project B end which saves them and transmits it back to my Django rest api for saving it in the database. -
sending websocket messages from my dockerized backend to my dockerized frontend
I'm sending websocket messages from an external script to a django page and it works fine until i dockerize it. my django page (my frontend) is running on port 80, and my frontends docker-compose states ports: - 80:80 hostname: frontend and my backend.py file is trying to connect with this line async with websockets.connect('ws://frontend:80/ws/endpoint/chat/', ping_interval=None) as websocket: so i think my backend should be able to see it. its able to connect when not dockerized with async with websockets.connect('ws://localhost:80/ws/endpoint/chat/', ping_interval=None) as websocket: the error i get when dockerized is Traceback (most recent call last): File "/usr/local/lib/python3.9/multiprocessing/process.py", line 315, in _bootstrap self.run() File "/usr/local/lib/python3.9/multiprocessing/process.py", line 108, in run self._target(*self._args, **self._kwargs) File "//./main.py", line 531, in send_SMS_caller asyncio.run(SendSMS()) File "/usr/local/lib/python3.9/asyncio/runners.py", line 44, in run return loop.run_until_complete(main) File "/usr/local/lib/python3.9/asyncio/base_events.py", line 647, in run_until_complete return future.result() File "//./main.py", line 496, in SendSMS async with websockets.connect('ws://frontend:80/ws/endpoint/chat/', ping_interval=None) as websocket: File "/usr/local/lib/python3.9/site-packages/websockets/legacy/client.py", line 637, in __aenter__ return await self File "/usr/local/lib/python3.9/site-packages/websockets/legacy/client.py", line 655, in __await_impl_timeout__ return await self.__await_impl__() File "/usr/local/lib/python3.9/site-packages/websockets/legacy/client.py", line 662, in __await_impl__ await protocol.handshake( File "/usr/local/lib/python3.9/site-packages/websockets/legacy/client.py", line 329, in handshake raise InvalidStatusCode(status_code, response_headers) websockets.exceptions.InvalidStatusCode: server rejected WebSocket connection: HTTP 404 chatgpt suggested i point to the specific ip of my hostmachine which i do … -
How to delete oldest data in table if more than 5 row using django?
If data in table more than 5 row I want to delete oldest row such as. id value 1 a1 <= delete 2 a2 3 a3 4 a4 5 a5 6 a6 I want to keep new 5 rows which is id 2-6 and delete oldest row which is id 1. I use this code. objects_to_keep = Data.objects.filter(key=key).order_by('id')[:5] Data.objects.exclude(pk__in=objects_to_keep).delete() It show error like this. NotSupportedError at /device/ (1235, "This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'") How to fix it?