Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to rename field names in Django
There are two models. CaseRequest is the list of requests and each containing the name and birth date of the applicant. Also, there is the Case table, and it's just a collection of all people. The idea is the following. Each CaseRequest must specify whether the same name and date of birth exist in the Case table. If it exists, CaseRequest displays yes, if it doesn't exist - no. In other words, we should know, is there the same name and date in another table or not. Models.py class CaseRequest(models.Model): name = models.CharField(max_length=255) datebirth = models.DateField() status = models.CharField(max_length=255) def __str__(self): return self.name def get_absolute_url(self): return reverse('caserequest') class Case(models.Model): name = models.CharField(max_length=255) datebirth = models.DateField() def __str__(self): return self.name + ' | ' + str(self.datebirth) def get_absolute_url(self): return reverse('case_list') Views.py class CaseRequestView(ListView): model = CaseRequest template_name = 'caserequest.html' CaseRequest.html <div> {% for caserequest in object_list %} <div> <p>{{ caserequest.name }}, {{ caserequest.datebirth }}</p> <p>Status: {{ caserequest.status }}</p> <!-- It's required to show YES or NO here--> </div> </div> For instance, we have the Case table: name datebirth Jon Won 01.05.1998 Douglas Hensley 10.10.1943 Ben Wall 14.12.2000 Hog Pen 11.04.2012 And the following result in CaseRequest must be: name datebirth status … -
Django Forms: How to set choose select option class and set disabled or selected in forms.py
Is it possible in a simple way? I have in my forms Class class ExampleForm(forms.ModelForm): class Meta: CHOICES = (('Option 1', 'Option 1'), ('Option 2', 'Option 2'),) widgets = { 'classification': forms.Select(choices=CHOICES, attrs={'class':'form-select'}), } but i want to have <select> <option class="some-class" value="option 1" disabled>option 1</option> ... </select> How to add a class in options and also disabled? -
Complex constraint in Django with Q Objects
Two players can register for a tennis tournament which offers the doubles discipline (2 players compete against 2 other players). But there are some constraints: The same player may not register as player_01 for the same competition twice (same for player_02) A player may not register as player_01 if already registered as player_02 (with different partner) for the same competition (and vice versa) class Registration(models.Model): class Meta: abstract = True competition = models.ForeignKey(Competition, on_delete=models.CASCADE) class DoubleRegistration(Registration): class Meta: constraints = [ # 1. The same player may not register as player_01 for the same competition twice (same for player_02) models.UniqueConstraint( fields=['competition', 'player_01'], name='double_registration_unique_pl01'), models.UniqueConstraint( fields=['competition', 'player_02'], name='double_registration_unique_pl02'), # 2. A player may not register as player_01 if already registered as player_02 (with different partner) for the same competition (and vice versa) models.CheckConstraint( check=~Q(player_01=F('player_02') , competition=F('competition')), name='double_registration_pl01_already_registered'), models.CheckConstraint( check=~Q(player_02=F('player_01'), competition=F('competition')), name='double_registration_pl02_already_registered'), ] player_01 = models.ForeignKey(Player, on_delete=models.CASCADE, related_name = 'doubles_player_01') player_02 = models.ForeignKey(Player, on_delete=models.CASCADE, related_name = 'doubles_player_02') While the first constraint seems to work fine, the second constraint does not work. I am still able to first register Adam as player_01 and Kain as player_02 (which is fine) but then also register Adam as player_02 and Kain as player_01. Since the second … -
How to add a field to model with a decorator?
I'd like to add foreign keys to virtually every model in my app to allow different Sites. For this I think it would be nice to use decorators, because I will be able to only add those FKs under certain conditions (e.g. if Sites is installed). Unfortunately my attempt doesn't do anything: def add_site_fk_field(model_to_annotate: models.Model): """Add FK to Site to Model""" model_to_annotate.site = models.ForeignKey(Site, on_delete=models.CASCADE) return model_to_annotate @add_site_fk_field class Test(models.Model): ... Is it somehow possible to do this? I prefet not to use abstract classes. -
pip install mod_wsgi issue
install is failing and cant figure out why. ive spent a lot of time researching this issue and half of the people are saying the apache24 folder is in the wrong place, which ive double checked its correct. and the other half say its because windows sdk tools are not installed, which ive double checked they are. PS C:\Users\Mlong\Downloads\ZTP 4\ZTP> pip install mod_wsgi Collecting mod_wsgi Using cached mod_wsgi-4.9.4.tar.gz (497 kB) Preparing metadata (setup.py) ... done Building wheels for collected packages: mod_wsgi Building wheel for mod_wsgi (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─> [31 lines of output] running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-3.10 creating build\lib.win-amd64-3.10\mod_wsgi copying src\__init__.py -> build\lib.win-amd64-3.10\mod_wsgi creating build\lib.win-amd64-3.10\mod_wsgi\server copying src\server\apxs_config.py -> build\lib.win-amd64-3.10\mod_wsgi\server copying src\server\environ.py -> build\lib.win-amd64-3.10\mod_wsgi\server copying src\server\__init__.py -> build\lib.win-amd64-3.10\mod_wsgi\server creating build\lib.win-amd64-3.10\mod_wsgi\server\management copying src\server\management\__init__.py -> build\lib.win-amd64-3.10\mod_wsgi\server\management creating build\lib.win-amd64-3.10\mod_wsgi\server\management\commands copying src\server\management\commands\runmodwsgi.py -> build\lib.win-amd64-3.10\mod_wsgi\server\management\commands copying src\server\management\commands\__init__.py -> build\lib.win-amd64-3.10\mod_wsgi\server\management\commands creating build\lib.win-amd64-3.10\mod_wsgi\docs copying docs\_build\html\__init__.py -> build\lib.win-amd64-3.10\mod_wsgi\docs creating build\lib.win-amd64-3.10\mod_wsgi\images copying images\__init__.py -> build\lib.win-amd64-3.10\mod_wsgi\images copying images\snake-whiskey.jpg -> build\lib.win-amd64-3.10\mod_wsgi\images running build_ext building 'mod_wsgi.server.mod_wsgi' extension creating build\temp.win-amd64-3.10 creating build\temp.win-amd64-3.10\Release creating build\temp.win-amd64-3.10\Release\src creating build\temp.win-amd64-3.10\Release\src\server C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.34.31933\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Ic:\Apache24/include -IC:\Users\Mlong\scoop\apps\python\current\include -IC:\Users\Mlong\scoop\apps\python\current\Include -IC:\Program Files (x86)\Microsoft … -
Vulnerability issue Accept-Language headers are cached in order to avoid repetitive parsing on AWS ECR
I am getting this below high severity vulnerability issue on my AWS ECR image, I don't know what is causing it since I am using the latest version on Docker container of Django i.e 4.1.6. In Django 3.2 before 3.2.17, 4.0 before 4.0.9, and 4.1 before 4.1.6, the parsed values of Accept-Language headers are cached in order to avoid repetitive parsing. This leads to a potential denial-of-service vector via excessive memory usage if the raw value of Accept-Language headers is very large. -
Django: Overriding Postgres Database wrapper to set search path throws error
I want to establish a connection with a postgres database in django. As it doesn't provide support for postgres schemas I am trying to set the search_path immediately after establishing a connection. To acheive this I have subclassed the DatabaseWrapper class and overridden the _cursor method as below: from django.db.backends.postgresql.base import DatabaseWrapper class DatabaseWrapper(DatabaseWrapper): def __init__(self, *args, **kwargs): super(DatabaseWrapper, self).__init__(*args, **kwargs) def _cursor(self, name=None): cursor = super(DatabaseWrapper, self)._cursor(name) cursor.execute('SET search_path = schema_name') return cursor Now the above code works fine for the application code that we have written but when I try access the detail screen of any object in the admin panel of django, I get the below error trace: File "/Users/azharuddin.syed/Desktop/application/custom_db_engine/base.py", line 13, in _cursor cursor.execute('SET search_path = schema_name') File "/Users/azharuddin.syed/Desktop/application/venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 98, in execute return super().execute(sql, params) File "/Users/azharuddin.syed/Desktop/application/venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/Users/azharuddin.syed/Desktop/application/venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "/Users/azharuddin.syed/Desktop/application/venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/Users/azharuddin.syed/Desktop/application/venv/lib/python3.9/site-packages/django/db/utils.py", line 90, in exit raise dj_exc_value.with_traceback(traceback) from exc_value File "/Users/azharuddin.syed/Desktop/application/venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) django.db.utils.ProgrammingError: syntax error at or near "SET" LINE 1: ...6171701248_sync_1" NO SCROLL CURSOR WITH HOLD FOR SET search... If I understand … -
Crispy forms label inside of field
Using Bootstrap5, Django and Crispy Forms to create a calculator application. Application works as expected however I want to make changes to the appearance of the forms. I've already removed the required field asterisk by simply adding the following to the CSS file: .asteriskField { display: none; } But now I want to place the label inside the field which requires a different approach that I'm currently unable to understand despite extensive research. Having used Inspect in Chrome I can see that the label is of course a separate element but one housed within the field to achieve the given effect. Current Form Desired result Settings.py (excerpt) CRISPY_TEMPLATE_PACK = 'bootstrap5' Forms.py (excerpt) class InvestmentForm(forms.Form): starting_amount = forms.ChoiceField(choices=STARTING_AMOUNT) deposit_amount = forms.FloatField() trade_in_value = forms.FloatField() number_of_years = forms.FloatField() credit_score = forms.ChoiceField(choices=CREDIT_SCORE) state = forms.ChoiceField( label='State', choices=[(zipcode, zipcode) for zipcode in StateTax.objects.values_list('zipcode', flat=True).distinct()] ) Index.html (excerpt) <div class="row justify-content-center"> <h5 class="text-center"> Enter details below to see your estimate</h5> </div> <div class="col-md-8 mx-auto"> <form action="" method="POST"> {% csrf_token %} {{ form|crispy }} <br> <button class="btn btn-primary" type="submit">Calculate</button> </form> <br> </div> </div> -
Can I use DRF-SPECTACULAR for external API?
Currently using drf-spectacular with no issues on my site. However, I need to also document some APIs for separate app. Is it possible to use a json or yaml file to produce some swagger/redoc documentation? -
Django: In a ModelManager, how do I access a constant defined inside the related Model?
I have, for example, an Enum defined inside a Model. That model uses, and therefore imports, a ModeLManager. In that ModelManager, I'd like to access the Enum that I defined inside the Model; but I can't import the Model there or I'd get a circular dependency error. An example of the issue: Managers.py class CardManager(models.Manager): def spades(self): return self.filter(suit=2) Models.py from foo.managers import CardManager class Card(models.Model): class Suit(models.IntegerChoices): DIAMOND = 1 SPADE = 2 HEART = 3 CLUB = 4 suit = models.IntegerField(choices=Suit.choices) objects = CardManager() This code works perfectly well, but instead of having suit=2, I'd prefer to have something like suit=Card.Suit.SPADE. I can't find a way to make that reference work, though, as I can't import Card into Managers.py. Should I be defining the enum inside the ModelManager instead of the Model? All examples I've come across define them in the Model instead. -
{% load static%} does not work for extended Django html files
I am trying to load a CSS file located in my static files onto an extended django html file. The {% load static %} works in the base.html template but does not work anywhere else. I'm not sure how to proceed Here is my code base.html {% load static %} <!doctype html> <html> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href='https://unpkg.com/boxicons@2.0.9/css/boxicons.min.css' rel='stylesheet'> <link rel="stylesheet" href="{% static 'styles/style.css' %}" /> <title>My Site</title> {% block htmlhead %} {% endblock htmlhead %} </head> <body> {% include 'sidebar.html' %} {% include 'navbar.html' %} {% block content %}{% endblock %} <script src="https://cdn.jsdelivr.net/npm/apexcharts"></script> <script src="{% static 'js/script.js' %}"></script> </body> </html> here is an extended django html template {% extends 'base.html' %} {% load static %} {% block content %} <main id="content"> <h1 class="title">Dashboard</h1> <ul class="breadcrumbs"> <li><a href="#">Home</a></li> <li class="divider">/</li> <li><a href="#" class="active">Dashboard</a></li> </ul> <div class="info-data"> </div> <div class="project-home-data"> <div class="project-content-data"> <div class="project-head"> <h3>Your Tickets</h3> </div> <div class="project-body"> <table> <thead> <tr> <th>Project Name</th> <th>Description</th> <th></th> <th>Created</th> </tr> </thead> <tbody> <tr> <td><a href="">Hello</a></td> <td>Hello</td> <td></td> <td>Hello</td> </tr> </tbody> </table> <p>Showing 1 to 5 of 5 entries </p> <div class="pagination"> <a href="#">&laquo;</a> <a href="#">1</a> <a href="#">2</a> <a href="#">3</a> <a href="#">4</a> <a href="#">5</a> <a href="#">6</a> <a href="#">&raquo;</a> </div> … -
Validate an email in Python/Django
I'm receiving an email from a http request and I need to validate it. The email filed should have the format: "example@domain.com". The email nmame con contain special characters like [~, !, #, $, %, ^, &, *, _], but may not contain [@, (, ), .]. The email domain and subdomain should not contain special characters. I'm trying to solve this with regular expressions but I don't have so much experience with this topic. -
How to build API that will return HTML for the site and JSON for other clients
I have started learning DRF just a while ago and had a little question - how can I code one API that will return HTML for the site that I am currently working on and return JSON format for other "clients"(e.g. mobile apps, desktop, etc)? I have tried to search for this information, but didn't found any answering content. The only way I see is to create default Django views for the site and create separated API's for other requests. Can anybody tell me if I am right and need to do so, or there is some code that is solving my problem? -
'parsererror' error In MYSQL Axaj Django upload in chunks
I want to upload a file in chunks, and it works on SQLite but i wont work with MYSQL, and it uploads the file only till 10mb/11mb. Debug false/true gives me the same error JS: $.ajax({ xhr: function () { var xhr = new XMLHttpRequest(); xhr.upload.addEventListener('progress', function (e) { if (e.lengthComputable) { if (self.file.size < self.max_length) { var percent = Math.round((e.loaded / e.total) * 100); } else { var percent = Math.round((uploadedChunk / self.file.size) * 100); } $('.progress-bar').css('width', percent + '%') $('.progress-bar').text(percent + '%') } }); return xhr; }, url: '/create-post', type: 'POST', dataType: 'json', cache: false, processData: false, contentType: false, data: formData, error: function (xhr) { alert(xhr.statusText); }, success: function (res) { if (nextChunk < self.file.size) { // upload file in chunks existingPath = res.existingPath self.upload_file(nextChunk, existingPath); } else { // upload complete $('.textbox').text(res.data); alert(res.data) } } }); }}; Views: https://imgur.com/a/FThSXAO All of this gives me parsererror Nothing else... -
Django - after sign-in template don't know that user is authenticated
Below code probably works (no errors present): views.pl class SignInView(View): def get(self, request): return render(request, "signin.html") def post(self, request): user = request.POST.get('username', '') pass = request.POST.get('password', '') user = authenticate(username=user, password=pass) if user is not None: if user.is_active: login(request, user) return HttpResponseRedirect('/') else: return HttpResponse("Bad user.") else: return HttpResponseRedirect('/') ....but in template: {% user.is_authenticated %} is not True. So I don't see any functionality for authenticated user. What is the problem? -
DjangoRestFramework, how to add optional field not coming from model to serializer
I have a model like this: class Camper(models.Model): location = models.PointField() name = models.CharField(max_length=255) and a viewset like this: class CamperViewSet(viewsets.ModelViewSet): ... def retrieve(self, request, *args, **kwargs): """Retrieve a Camper instance.""" show_weather = request.query_params.get('showWeather', False) instance = self.get_object() if show_weather: lat = instance.location.y lon = instance.location.x instance.weather = getWeatherFromLatLon(lat, lon) serializer = self.get_serializer(instance) return Response(serializer.data) So when I request /api/campers/8?showWeather=true I make another request in my view to get the weather from the current position. How do I add it to my serializer ? It's an optional field so I need to manage this and it's only used in /campers/id so it will not be used in list/create/put/etc My serializer looks like this: class CamperSerializer(serializers.ModelSerializer): camper_id = serializers.IntegerField(source='id') class Meta: model = Camper fields = ('camper_id', 'name', 'location') -
URL for Django filtering get requests
I'm making a filtering function for a database I'm working with. I'm wondering how I can access the request url. Here is the code for the models. from django.db import models class User(models.Model): username = models.CharField(max_length=20, null=True) account_type = models.CharField(max_length=30, null=True) first_name = models.CharField(max_length=30, null=True) last_name = models.CharField(max_length=30, null=True) email = models.EmailField(max_length=254, null=True) class Interest(models.Model): interest = models.CharField(max_length=200, null=True) listing_account = models.ForeignKey(ListingAccount, related_name='interests', on_delete=models.CASCADE, null=True) def __str__(self): return f"{self.interest}" Below is the filtering function in views.py. How can I find the URL path to this? class AccountFilterViewSet(generics.ListAPIView): queryset = ListingAccount.objects.all() serializer_class = ListingAccountSerializer filter_backends = [filters.SearchFilter] search_fields = ['first_name'] -
How do I properly set up a React app using Vite with my Django backend?
I've built my Django backend, then created a new app called Frontend. In the frontend folder I started a Vite app called "static" which includes my src folder and other files. When I create a build using npm run build a dist folder is created. I am able to run this project on localhost:5173 but when I want to run on Django (http://127.0.0.1:8000/) I get a blank white screen with errors. The errors are linked --> console errors here Has anyone gone through this process? -
Django Annotate Count
Could someone help me to understand why func Count calculates 1 for the actor that does not have any publicated scene?: actors = Actor.objects.filter(state=Actor.State.PUBLISHED)\ .annotate(scenes_cnt=Count('scenes', filter=Q(state=Scene.State.PUBLISHED))) I have one actor who has only one scene with state=Scene.State.PREVIEW but the code above calculates scenes_cnt=1 for this actor. I'm confused. Thanks in advance! I try to calculate publicated scenes for actors. Expect to get scenes_cnt=0 if actor does not have any scene with state=Actor.State.PUBLISHED -
Django: Object of type Decimal is not JSON serializable
I am trying to pass in some more data to the jwt token authentication, i have written a Serialize for this and passed in some other fields like full_name, image, pin etc now i am trying to pass in the wallet field which is a DecimalField in my Model, then i am getting this error. Object of type Decimal is not JSON serializable how do i fix this? token['wallet'] = user.profile.wallet Complete Serializer class MyTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super().get_token(user) # Add custom claims token['username'] = user.username token['email'] = user.email token['full_name'] = user.profile.full_name token['bio'] = user.profile.bio token['country'] = user.profile.country token['image'] = user.profile.image.url token['address'] = user.profile.address token['phone'] = user.profile.phone token['website'] = user.profile.website token['pin'] = user.profile.pin token['verified'] = user.profile.verified token['wallet'] = user.profile.wallet # ... return token -
DjangoRestFramwork how to override ModelViewSet get method
I have a model like this : class AccountViewSet(viewsets.ModelViewSet): """ A simple ViewSet for viewing and editing accounts. """ queryset = Account.objects.all() serializer_class = AccountSerializer permission_classes = [IsAccountAdminOrReadOnly] How do I override the get method so when I hit /api/accounts/8 I can add some code before returning the 8th account ? -
Django Admin select_related issue
I'm trying to select_related for a bunch of assets in the Django admin. These assets are tied to a product, which in turn has a separate Company and Category model. I defined the string method like so in the Product class: def __str__(self): if self.company: return f"{self.category.name} | {self.company.name} | {self.name}" return f"{self.category.name} | {self.name}" However, when I check debug toolbar in the Django admin, I see that a bunch of extra queries are made because of this. products\models.py in __str__(53) return f"{self.category.name} | {self.company.name} | {self.name}" I have the following get_queryset method defined in the ModelAdmin: def get_queryset(self, request): qs = super().get_queryset(request).select_related( 'product', 'product__category', 'product__company') if request.user.is_superuser or request.user.is_staff: return qs return qs.filter(user=request.user) Is there a fix for this? Am I doing it wrong? -
How do you store an API key (token) client side without the user being able to see/access it?
I am working on a project that is handling sensitive customer information. Obviously security is a high priority. We have recently created an API that we want to use to be able to access the database to access / modify the data. What is the best way to store an API token client side? We currently are using the meta tag of the html template file to store the csrf token, but we do not want the API token to be visible. Here is the code for the csrf token and it works. //Capture and store the csrf Token useEffect(() => { const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content'); setToken(csrfToken); console.log({sessionToken, csrfToken}); }, []); Here is the tag for the index file we are using as a template <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="csrf-token" content="{{ csrf_token }}"> <meta name="api-token" content="{{ request.session.api_token }}"> </head> This also works, but then the API token is visible if someone inspects the page. We are using a Django / Python backend and a React front end. Would this involve the use of cookies? Or does it get more complicated than that? Any help would be greatly appreciated. Let me know if you need to see … -
Joining a table to itself in django ORM
I am creating a room booking system in Django and need a way to find overlaps in a reservation. I have come up with this raw query: select distinct y.reservation_base_id as id from app_reservation x inner join app_reservation y on x.reservation_base_id != y.reservation_base_id and x.id != y.id and x.start <= y.stop and y.start <= x.stop where x.reservation_base_id = %s; Here 'app_reservation' is an actual reservation that has the info about start and stop of the reservation. A reservation links to a reservation base. A reservation base has meta information about the reservation ie: title, description. This query works, however i would like to translate it to Django orm so i can easily modify it, and make it more flexible. I have looked in to Subquerying and Q-nodes, but i have not found something that join a model to itself. Any help would be greatly appreciated. -
Is it possible to add days to the date in the template?
I have today's date in my template, which is in a loop. I want to add a counter to the cycle so that in the template I don't have today's date, but date + 1 day, date + 2 days, and so on. {% for day_week_list in set_day_week %} <div class="card mb-2"> <div class="card-header"> {{ day_week_list }} {{ day_data|date:'d.m' }} </div> <div class="card-body">