Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to rename "admin" static files in Django?
When loading up the Django admin pages, you load in the default Django admin css / js files. For example, example.com/staticfiles/admin/css/base.css. I've enabled a default Amazon WAF (firewall) rule that blocks all access to pages that have the word "admin" in their URL. This has been great so far -- as most bots love looking for /admin domains. However, this ends up blocking the Django admin. I'm able to rename the Django admin url to /manager using one line of code in urls.py, however I can't figure out how to to change the admin static files' filepath. I'm currently getting raw, unstyled HTML in my admin as all the static files are blocked. Ideally, in settings.py I could write: ADMIN_FOLDER_NAME = 'manager' and then example.com/staticfiles/admin/css/base.css would get rewritten to example.com/staticfiles/manager/css/base.css. How can I tell Django to look in a different folder for admin files? -
Django keep one element by group and then use property on this queryset
I have a model like this one: class Extension(models.Model): name = models.CharField(max_length=32) version = models.CharField(max_length=16) @property def path(self): return something I would like to get an Extension queryset containing only the last version for each name and then get a tuple (name, path) for each of these last recent Extension. I tried latests = Extension.objects.values('name').annotate(last=Max('version')) but it gave me a dict without the properties access How can i do that? -
python ForeignKey relation with user shows this error NOT NULL constraint failed: music_song.performer_id
Fellow programmers, I am getting a error NOT NULL constraint failed: music_song.performer_id I want the performer field to be the user who is creating the song but its not happening I have tried a lot can you guys please help me out with it models.py class Song(models.Model): name = models.CharField(_("Name"), max_length=50) song = models.FileField(_("Song"), upload_to=None, max_length=100) song_image = models.ImageField(upload_to=None, height_field=None, width_field=None,max_length=100) likes = models.IntegerField(_("Likes"),default=0) views = models.IntegerField(_("Views"),default=0) performer = models.ForeignKey(settings.AUTH_USER_MODEL,verbose_name=_("Performed By"),related_name='artist_in_song',on_delete=models.CASCADE) serializers.py class SongCreateSerializer(serializers.ModelSerializer): performer = serializers.SerializerMethodField() def get_performer(self,obj): return obj.performer.id class Meta: model = Song fields = ['id','name','song','song_image','likes','views','performer'] read_only_fields = ('performer','likes','views') views.py class SongCreateView(generics.CreateAPIView): queryset = Song.objects.all() serializer_class = SongCreateSerializer permission_classes = [IsAuthenticated] -
Is there something like Laravel Sanctum but in Django?
Im working on an API in Django Rest framework that is consumed by a SPA in Vue.js and the authorization approach from Laravel Sanctum looks like the holy grail of SPA authentication. -
idea for starting Inventory management app with django
I want to create a simple inventory management app with django which user can add item in inventory and also exit item as much as he want and then we must can take a report from number of existing items in inventory any idea that how should i start? -
Add data/model instance to M2M field dynamically when creating model with dictionary
I'm trying to create a model with m2m field using a dictionary. Something like: data = {fieldA: "hello", fieldB: "world", m2m: [ModelInstance, ]} model_instance.objects.create(**data) I tried adding the m2m value I'm trying to set in an array but I keep getting the exception TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. -
How do I replicate Django Admin-like CRUD for related objects?
I was able to add a PLUS button to a select widget in a CreateView like in Django Admin. I would like to add objects to the related model using the related model's CreateView by opening a new window using the PLUS button in the CreateView of the child model. After saving the related object, I should be able to go back to the previous CreateView to finish my entry. Any tutorials or guides on how to this like in Django Admin? -
Why does this recursion error appear in pre-installed code?
So I am fairly new to coding with python and Django, but while working on a website I ran into this problem: "File "/Users/home/first_web/myenv/lib/python3.7/site-packages/django/urls/resolvers.py", line 131, in _check_pattern_startswith_slash if regex_pattern.startswith(('/', '^/', '^\/')) and not regex_pattern.endswith('/'): RecursionError: maximum recursion depth exceeded while calling a Python object" I have tried looking at the code to see if I could solve it, but to my untrained eye I don't really notice anything wrong (btw, I didn't write the code referenced in the error). Below you can see all the the referenced file's lines of code, but as mentioned above the error is around line 131. """ This module converts requested URLs to callback view functions. URLResolver is the main class here. Its resolve() method takes a URL (as a string) and returns a ResolverMatch object which provides access to all attributes of the resolved URL match. """ import functools import inspect import re import string from importlib import import_module from urllib.parse import quote from asgiref.local import Local from django.conf import settings from django.core.checks import Error, Warning from django.core.checks.urls import check_resolver from django.core.exceptions import ImproperlyConfigured, ViewDoesNotExist from django.utils.datastructures import MultiValueDict from django.utils.functional import cached_property from django.utils.http import RFC3986_SUBDELIMS, escape_leading_slashes from django.utils.regex_helper import normalize from … -
Can't override gis admin templates
I'm using Django 2.2.12 and have the following in settings.py: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates') ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Admin templates should be overridable by creating the appropriate structure inside the templates directory in my project root. In fact, I have been able to successfully override registration templates, but somehow I can't manage to do the same with gis admin templates. Templates dir looks like this: templates --gis ----admin ------openlayers.html --registration ----password_reset_confirm.html # This overrides just fine -
Customize password reset functionality in the django admin for custom user accounts
I am using the default admin interface provided from django but with custom user models. The admin should change the password to a random value in case a user forgets its. Django provides this function by following the link called "this form" as seen in the picture below. When clicking the link it redirects to the following page. How can i modify the code that gets executed once i submit this form? I'd like to add some custom entries in the database once the password gets changed using this form. -
How to assign custom color to progress bar bootsrap 4
Guys i have progressbar: a=50 <div class="progress"><div class="progress-bar" style="width:{{a}}%">{{a}} %</div> </div> How can i assign custom color to progress bar based on condititon in CSS ? : if a<50 color red if a>50 but less than 70 color orange if a>70 color green Would appreciate your help. -
Django attribute of most recent reverse relation
I have two models: class Test(models.Model): test_id = models.CharField(max_length=20, unique=True, db_index=True) class TestResult(models.Model): test = models.ForeignKey("Test", to_field="test_id", on_delete=models.CASCADE) status = models.CharField(max_length=30, choices=status_choices) with status_choices as an enumeration of tuples of strings. Some Test objects may have zero related TestResult objects, but most have at least one. I want to filter Test objects based on their most recent TestResult status. I have tried this: queryset = Test.objects.all() queryset = queryset.annotate(most_recent_result_pk=Max("testresult__pk")) queryset = queryset.annotate(current_status=Subquery(TestResult.objects.filter(pk=OuterRef("most_recent_result")).values("status")[:1])) But I get the error: column "u0.status" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: ...lts_testresult"."id") AS "most_recent_result_pk", (SELECT U0."status... I can find the most recent TestResult object fine with the first annotation of the pk, but the second annotation breaks everything. It seems like it ought to be easy to find an attribute of the TestResult object, once its pk is known. How can I do this? -
Django:Error upon having more than than 3 models in one view
am trying to create a dashboard template page having a summary of the system model.But when i exceed more than three models in the view,it shows up an error.How do i go about this? def dashboard(request): return render(request=request, template_name = 'main/admin.html', context = { "teachers_list": Teacher.objects.all(), "stream_list": Stream.objects.all(), "fees_list":Fees.objects.all(), "books_list":Book.objects.all() } ) -
Mutual relationship between two Django models
I have the (simple, I suppose) need of having a situation like so: there are many profiles, and there are many ensembles, and each profile has to be able to be part of one or more ensembles. This is my code: class Ensemble(models.Model): ensembleName = models.CharField(max_length=200) members = models.ManyToManyField('Profile', related_name='members') def __str__(self): return self.ensembleName class Profile(models.Model): ensemble = models.ForeignKey(Ensemble, on_delete=models.CASCADE, blank=True, null=True) [...] It all works well, but to an extent. From the Django administration I can, from the 'ensemble' page, select its members. I can also select, from the 'profile' page, which ensembles that profile belongs. The issue is: they are not synchronised: if I add a profile to an ensemble via the 'profile' page this is not reflected in the 'ensemble' page and the other way round, i.e. in the 'profiles details' page I don't see the ensemble to which I previously assigned that profile from the 'ensemble' page. -
How to fix ERROR while installing WSGI for PYTHON
I can't install WSGI for Python. I have tried lots of things. I have installed the latest versions of pip, python, apache, setuptools. I can't understand why WSGI is not installing I have started learning python a few days ago on my own. I have watched lots of videos and i've read lots of informations in different forums. But i couldn't solve this problem Maybe i'm doing something wrong D:\It\Console2>pip install mod_wsgi Collecting mod_wsgi Using cached mod_wsgi-4.7.1.tar.gz (498 kB) Building wheels for collected packages: mod-wsgi Building wheel for mod-wsgi (setup.py) ... error ERROR: Command errored out with exit status 1: command: 'd:\it\python\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\TheFlash\\AppData\\Local\\Temp\\pip-install-ih8ke_\\mod-wsgi\\setup.py'"'"'; __file__='"'"'C:\\Users\\TheFlash\\AppData\\Local\\Temp\\pip-install-55ih8ke_\\mod-wsgi\\setup.py'"'"';f=getattr(tokeniz '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheeld 'C:\Users\TheFlash\AppData\Local\Temp\pip-wheel-xh383iwl' cwd: C:\Users\TheFlash\AppData\Local\Temp\pip-install-55ih8ke_\mod-wsgi\ Complete output (33 lines): d:\it\python\lib\distutils\dist.py:261: UserWarning: Unknown distribution option: 'bugtrack_url' warnings.warn(msg) running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-3.6 creating build\lib.win-amd64-3.6\mod_wsgi copying src\__init__.py -> build\lib.win-amd64-3.6\mod_wsgi creating build\lib.win-amd64-3.6\mod_wsgi\server copying src\server\apxs_config.py -> build\lib.win-amd64-3.6\mod_wsgi\server copying src\server\environ.py -> build\lib.win-amd64-3.6\mod_wsgi\server copying src\server\__init__.py -> build\lib.win-amd64-3.6\mod_wsgi\server creating build\lib.win-amd64-3.6\mod_wsgi\server\management copying src\server\management\__init__.py -> build\lib.win-amd64-3.6\mod_wsgi\server\management creating build\lib.win-amd64-3.6\mod_wsgi\server\management\commands copying src\server\management\commands\runmodwsgi.py -> build\lib.win-amd64-3.6\mod_wsgi\server\management\commands copying src\server\management\commands\__init__.py -> build\lib.win-amd64-3.6\mod_wsgi\server\management\commands creating build\lib.win-amd64-3.6\mod_wsgi\docs copying docs\_build\html\__init__.py -> build\lib.win-amd64-3.6\mod_wsgi\docs creating build\lib.win-amd64-3.6\mod_wsgi\images copying images\__init__.py -> build\lib.win-amd64-3.6\mod_wsgi\images copying images\snake-whiskey.jpg -> build\lib.win-amd64-3.6\mod_wsgi\images running build_ext building 'mod_wsgi.server.mod_wsgi' extension creating … -
Calling DRF api within another view in django 2.2
I have an api view as: class part_detail(generics.RetrieveUpdateDestroyAPIView): queryset = parts.objects.all() serializer_class = parts_serializer I want to pass this as context in a detail view. Currently I am doing it as def part_detail(request, id): context = requests.get('http://localhost:8000/bon/part_detail/'+id+'/?format=json').json() return render(request, 'frontend/part_detail.html',context) But this will obliviously not work in production. How can I correctly call in apiview directly. -
Django, condition to check if query-set is empty
I want to check if items queryset is empty or not. order = Order.objects.get(customer=request.user.customer , complete=False) items = order.orderitem_set.all() flag = True if items == None: flag = False -
Stripe Token not generating
I am designing Stripe based Payment gateway with all CardNumber, CVC and Expiry as different elements in django. payment.html (html part): <div class="form-group"> <label for="cardnumber">Credit or debit card:</label> <div id="cardnumber"></div> </div> <div class="row"> <div class="col-6"> <div class="form-group"> <label for="cardexpiry">Expiry:</label> <div id="cardexpiry"></div> </div> </div> <div class="col-6"> <div class="form-group"> <label for="cardcvc">CVC:</label> <div id="cardcvc"></div> </div> </div> </div> payment.html (style part): <style media="screen"> .green{ border : solid green 1px; } .error{ border : solid red 1px; } .form-control::-moz-placeholder{ color: #aab7c4; } </style> payment.html (script part): var stripe = Stripe('pk_test_nnGYKgpxl7AmicqNbcoGIMqQ008d6IpXgw'); // Create an instance of Elements. var elements = stripe.elements(); // Custom styling can be passed to options when creating an Element. // (Note that this demo uses a wider set of styles than the guide below.) var style = { base: { color: '#32325d', fontFamily: '"Helvetica Neue", Helvetica, sans-serif', fontSmoothing: 'antialiased', fontSize: '16px', '::placeholder': { color: '#aab7c4' } }, invalid: { color: '#fa755a', iconColor: '#fa755a' } }; // Create an instance of the card Element. var cardnumber = elements.create('cardNumber', { classes : { base : "form-control", focus : "green", invalid : "error", }, style : style }); var cvc = elements.create('cardCvc', { classes : { base : "form-control", focus : "green", invalid : "error", … -
IndexError: list index out of range in Django Debug View
We updated our Django and Python versions to 3.0.6 and 3.8 respectively. Everything seems fine even when we run into Exceptions or errors locally everything is fine. However, whenever we run into issues on the server, we receive a basic "Internal Server Error" HTML page with no other content. We have a custom 500 page for showing errors so we can get a general idea of what the Exception is, however we cannot see the debug page that Django normally shows when DEBUG is set to True. Looking at the logs I can see that the exception is indeed thrown by whatever runs into the problem, however the debug view itself throws it's own Exception which I'd imagine is why we receive the default "Internal Server Error" page, as Django resorts to that when it can't render the Debug page. The stack trace is: File "/home/donationstore/env/lib/python3.8/site-packages/gunicorn/workers/sync.py", line 134, in handle self.handle_request(listener, req, client, addr) File "/home/donationstore/env/lib/python3.8/site-packages/gunicorn/workers/sync.py", line 175, in handle_request respiter = self.wsgi(environ, resp.start_response) File "/home/donationstore/env/lib/python3.8/site-packages/django/core/handlers/wsgi.py", line 133, in __call__ response = self.get_response(request) File "/home/donationstore/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 75, in get_response response = self._middleware_chain(request) File "/home/donationstore/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 36, in inner response = response_for_exception(request, exc) File "/home/donationstore/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 90, in response_for_exception response = … -
django templates loop two querysets
I am trying to get details of two querysets and display on my datatable. I can display details of first queryset but not of the second which is also dependent on the first queryset. My views.py function; def truck_list(request): q_data = quar_contacts.objects.all().filter(.....) hot_details = [] for d in q_data: h_details = truck_contacts.objects.filter(p_contacts=d.id) hot_details.append(h_details) my_list_data = zip(q_data, hot_details) data = {'quar_data': my_list_data} return render(request, 'syst/truck_list.html', data) I can print out details of the zip list as a tuple i.e data = tuple(my_list_data) and see the data. Then my truck_list template on the datatable body section : <tbody> {% for q_data, hot_details in quar_data %} <tr> <td>{{ q_data.last_name }}</td> <td>{{ q_data.first_name }}</td> <td>{{ q_data.age }}</td> <td>{{ q_data.sex }}</td> <td>{{ q_data.phone_number }}</td> <td>{{ hot_details.hotel_name}}</td> <td>{{ hot_details.date_check_in }}</td> </tr> {% endfor %} </tbody> How can i get the hot_details (hotel_name and date_checked_in) displayed on my datatable. How can I loop for each contact what hotel details are there. Is there an easier way of achieving this? -
Multiple items as a foreign key Django Models
I'm in the process of creating an e-commerce website with the django framework and have run into some problems with my models. Basically, this is a company which sells bags containing numerous different childrens toys. I've created a slugged page that users can access for more information about each toy and I want to have a list of toys that can be added to a bag, so that the same toy can be in 2 different bags. This way, the same toy object can be used multiple times if bags share a toy. I have managed to link one toy to a bag thus far, using a foreign key in the models. However, I'm not sure how to modify my code so that I can have multiple toy objects connected to a bag object. class Contents(models.Model): title = models.CharField(max_length=100, unique=True) description = models.CharField(max_length=1000) picture = models.ImageField(null=True) slug = models.SlugField(unique=True) def save(self, *args, **kwargs): super(Contents, self).save(*args, **kwargs) def __str__(self): return str(self.title) Above is the code I have so far for the toys model class Item(models.Model): pk_num = models.AutoField(primary_key=True) title = models.CharField(max_length=100, unique=True) price = models.FloatField() description = models.CharField(max_length=1000) picture = models.ImageField(null=True) release = models.DateTimeField(auto_now_add=True) slug = models.SlugField(unique=True) content = models.ForeignKey(Contents, on_delete=models.CASCADE) … -
JSON.parse() failing with the result of json_script template tag
I'm using the template tag json_script like in the docs This is my code: {{rules|json_script:"rules"}} <script lang="javascript"> const rules = JSON.parse(document.getElementById('rules').textContent) </script> This is the view function in django: def import_consumptions(request): try: rules = Rule.objects.all() rules = serializers.serialize('json', rules) context = {} context['title'] = 'Importar consumos' context['view_name'] = 'import_consumptions' context['menu_group'] = MENU_GROUP context['rules'] = rules return render(request, "import_consumptions.html", context) except: template = loader.get_template( 'pages/error-404.html' ) return HttpResponse(template.render(context, request)) The problem is what I get from that tag, which is something like this: [{\"model\": \"rules.rule\", \"pk\": 1, \"fields\": {\"string\": \"adm\", \"profile\": 40 ... So I get this error: VM1913:5 Uncaught SyntaxError: Unexpected token R in JSON at position 5 in the JSON.parse line Could someone help me? -
Django - Scheduled event
I would like the status of this model change when the current date exceeds the expiration_date. I was reading about background tasks and Asynchronous Tasks with Celery ... Am I going the right way? Is there a more direct way of doing this? If anyone can give me a tip or something to follow I would be grateful. Thanks for listening. class MyModel(models.Model): status = models.BooleanField... expiration_date = models.DateField.... [...] -
Trying to select the object from api call in django
I'm trying to make a call from an api and use the film's id to make a new call but the film's id is not the object's id. All the ways I tried to get this information either gave me the same film id for all objects. Any suggestions apis.py - Here I call search_film() to get the list of movies and then I save that data to a json file. I want to use that data to select the correct object to use the film's id in the get_film() function import requests import json def search_film(movie): movies_list = [] url = f"https://imdb-internet-movie-database-unofficial.p.rapidapi.com/search/{movie}" headers = { 'x-rapidapi-host': "imdb-internet-movie-database-unofficial.p.rapidapi.com", 'x-rapidapi-key': "bff6c04355msh46e32c3afb8d323p1eaeedjsnbf048a37783e" } response = requests.request("GET", url, headers=headers) titles = response.json() with open('film_data.json', 'w') as json_file: json.dump(titles, json_file, indent=4, sort_keys=True) for i in range(len(titles['titles'])): movies_list.append(titles['titles'][i]) return movies_list def get_film(): film_list = [] movie = "" url = f"https://imdb-internet-movie-database-unofficial.p.rapidapi.com/film/{movie}" headers = { 'x-rapidapi-host': "imdb-internet-movie-database-unofficial.p.rapidapi.com", 'x-rapidapi-key': "bff6c04355msh46e32c3afb8d323p1eaeedjsnbf048a37783e" } response = requests.request("GET", url, headers=headers) movie = response.json().beautiffy() return film_list views.py - I tried to create a button function to get the ID but that didn't work as planned. The id repeats for all objects. from django.shortcuts import render from .models import Film from .forms import … -
Reverse for 'land' not found. 'land' is not a valid view function or pattern name
app Url path('order-summary/', OrderSummaryView.as_view(), name='order-summary'), project path('', include('products.urls', namespace='products')), i know code is correct but i dont know which is miss