Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I maintain a modified version of a Python library and ensure that my application installs this version automatically using requirements.txt?
I want to avoid manually editing the library code each time I install dependencies and is there a way to get future updates to the library while still preserving my changes? I am currently clueless on how can I achieve this. -
Error "SQLite backend does not support timezone-aware datetimes when USE_TZ is False" when saving DateField in Django
I am working on a Django project using an SQLite database and encountered the following error when trying to save records to the database: SQLite backend does not support timezone-aware datetimes when USE_TZ is False. In my model, I am using two DateField fields as follows: class Announcement(models.Model): date_start= models.DateField(null=True, blank=True) date_end = models.DateField(null=True, blank=True) In my code, I am assigning dates like this: from datetime import datetime, timedelta from coreapp.views.base.base_view import BaseView from coreapp.services import utils from announcement.models import Announcement class FormAnnouncement(BaseView): def post(self, request): form = utils.get_form_from_json(request) date_start = datetime.strptime(form['date_start'], "%Y-%m-%d").date() if 'date_start' in form and form['date_start'] else None date_end = datetime.strptime(form['date_end'], "%Y-%m-%d").date() if 'date_end' in form and form['date_end'] else None new_Announcement = Announcement.objects.get(id=announcement_id) new_Announcement.date_start = date_start + timedelta(days=1) new_Announcement.date_end = date_end + timedelta(days=1) new_Announcement.save() Relevant settings in settings.py: USE_TZ = False Database: SQLite From what I understand, this error usually occurs when working with DateTimeField or datetime, but in my case, I am only using DateField, which should handle just dates without the time component. Does anyone know what could be causing this error and how I can resolve it without changing USE_TZ in the settings.py file? -
AVIF for Django-imagekit?
Let’s say this is my code, powered by django-imagekit. from django.db import models from imagekit.models import ImageSpecField from imagekit.processors import ResizeToFill class Profile(models.Model): avatar = models.ImageField(upload_to='avatars') avatar_thumbnail = ImageSpecField(source='avatar', processors=[ResizeToFill(100, 50)], format='JPEG', options={'quality': 60}) How can this be modified to support AVIF as the target image format? I know JPEG and even WebM is supported. But I don’t think AVIF is. So is there any way this can be modified to accomplish it? -
How to Reuse MongoClient Connections Efficiently in Django with PyMongo?
I'm working on a project using Django version 3.0.8 and PyMongo version 3.11.3. Currently, for each incoming request, a new MongoClient is created, and the connection is destroyed once the request is processed. I think this approach incurs too much overhead due to the constant creation and destruction of connections. Is there a more efficient way to reuse MongoClient connections across requests? -
Why NextJs is making a xhr request instead of redirect to crossdomain url?
I have SSO based project. which main module is Django project (drf) and modules (they are separated projects preplanned to be drf+nextjs) supposed to authenticate and authorize requesting this module. Now in dev environment I have 3 servers Main app (auth_module - Django 14.2.12) localhost:8080 Store app backend (warehouse_backend - Django 5.1.1) localhost:8082 Store app frontend (warehouse_frontend - Nextjs 14.2.12) localhost:3000 So authentication flow happens the way below: When user enter http://localhost:3000/ warehouse_frontend axios GET request to /api/auth/user/ withCredentials=true 2.In /app/api/auth/user/route.js I have code that request to auth_module http://localhost:8080/api/user/ with cookies it should return user data if there is a access token in cookie. if there is no token in cookie it auth_module return 401 unauthorized response and in route.js I should redirect to http://localhost:8080/login?module=http://localhost:3000 auth_module login page it will handle the login with username and password. The Problem I face here in redirection route.js. Expected behavior is in browser the changes to http://localhost:8080/login?module=http://localhost:3000 but it fetchs url like xhr /app/layout.js export default function RootLayout({children}) { return ( <StoreProvider> <html lang="en"> <body> <Container maxWidth={'xl'} id={'root'}> <Header/> <UserFetcher/> {children} </Container> </body> </html> </StoreProvider> ) } UserFetcher.js useEffect(() => { (async () => { try { console.log('effect') const res = await axios('/api/auth/user', … -
Django ORM: Use an annotation's alias in subsequent annotations
I want to reuse an annotation's alias in subsequent expressions. How can I make Django generate SQL like the following: select a*b as x x/d as y from my_table; Note how x is simply referenced in x/d, rather than being expanded into (a*b)/d. Is this possible in Django? The reason I want to do this is because my queries are very large and complex. When using regular annotations, Django is duplicating large expressions many times and the resulting query output is becoming overly complex and difficult to debug and ensure correctness. -
How to delete a session key outside of a view?
I'm retrieving a session outside of a view by its session_key then I'm trying to delete a key from it like the following but it's not working: from importlib import import_module from django.conf import settings SessionStore = import_module(settings.SESSION_ENGINE).SessionStore my_session = SessionStore(session_key=my_session_key) del my_session["foo"] # also tried this but not working either: my_session.delete("foo") -
Django `collecstatic` returns `[Errno 13] Permission denied: '/code/static/admin/js/vendor/select2/i18n/pl.6031b4f16452.js.gz'`
I run my django app in Docker. I recently tried running collecstatic and instead was given this error code. Not sure what it means or what to do: >docker-compose exec web python manage.py collectstatic Traceback (most recent call last): File "/code/manage.py", line 22, in <module> main() File "/code/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.11/site-packages/django/core/management/base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.11/site-packages/django/core/management/base.py", line 458, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 209, in handle collected = self.collect() ^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 148, in collect for original_path, processed_path, processed in processor: File "/usr/local/lib/python3.11/site-packages/whitenoise/storage.py", line 162, in post_process_with_compression for name, compressed_name in self.compress_files(files_to_compress): File "/usr/local/lib/python3.11/site-packages/whitenoise/storage.py", line 199, in compress_files for compressed_path in compressor.compress(path): File "/usr/local/lib/python3.11/site-packages/whitenoise/compress.py", line 84, in compress yield self.write_data(path, compressed, ".gz", stat_result) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/whitenoise/compress.py", line 120, in write_data with open(filename, "wb") as f: ^^^^^^^^^^^^^^^^^^^^ PermissionError: [Errno 13] Permission denied: '/code/static/admin/js/vendor/select2/i18n/pl.6031b4f16452.js.gz' I read somewhere that it may have to do with root privileges but I'm not sure which root privileges or how to go about remedying it. -
Django - change form prefix separator
I'm using form prefix to render the same django form twice in the same template and avoid identical fields id's. When you do so, the separator between the prefix and the field name is '-', I would like it to be '_' instead. Is it possible ? Thanks -
Authlib JWT 'NoneType' object has no attribute 'startswith' error when fetching public key from JWKS
I'm working on a Django application that uses Authlib for JWT authentication, with Auth0 as the identity provider. I'm fetching the public key from the JWKS endpoint provided by Auth0 to validate the JWT. However, when decoding the token, I'm encountering the following error: Error: AttributeError: 'NoneType' object has no attribute 'startswith' This error occurs when processing the public key from the JWKS response. I suspect it might be an issue with how the key is fetched or decoded, particularly with the x5c field. I'm unsure how to handle this properly. Here's my current middleware implementation: import os import requests from authlib.jose import JsonWebToken from django.utils.deprecation import MiddlewareMixin from rest_framework.exceptions import AuthenticationFailed from dotenv import load_dotenv # Load environment variables from the .env file load_dotenv() class Auth0Middleware(MiddlewareMixin): def __init__(self, get_response=None): self.get_response = get_response self.jwt = JsonWebToken([os.getenv('ALGORITHMS', 'RS256')]) # Load algorithm from env self.jwks_url = f"https://{os.getenv('AUTH0_DOMAIN')}/.well-known/jwks.json" # Load Auth0 domain from env self.jwks = self.get_jwks() def get_jwks(self): response = requests.get(self.jwks_url) if response.status_code == 200: return response.json() raise AuthenticationFailed("Failed to fetch JWKS") def get_public_key(self, token): try: headers = self.jwt.decode(token, None, claims_cls=None) kid = headers.get('kid') for key in self.jwks['keys']: if key['kid'] == kid: raw_key = key.get('x5c', []) if not raw_key or not isinstance(raw_key, … -
How to make Django template variables work async?
I'm trying to apply Async approach to an existing Django project, updating views appears this error: django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. views.py @sync_to_async def get_educations(): return Education.objects.filter(highlight=True).order_by("-order") async def home(request): return render(request, "home.html", { "educations": await get_educations(), }) home.html <section class="d-flex flex-column"> <h3 class="section">Education</h3> {% for education in educations %} {% include "preview_education.html" %} {% endfor %} Trying with return [Education.objects.first()]works well. Any idea how to solve it ? -
django-tailwind not finding npm
I've been trying to install django-tailwind, using a windows computer, and I'm having trouble with the python manage.py tailwind install command. No matter what I try, I get this error: CommandError: It looks like node.js and/or npm is not installed or cannot be found. Visit https://nodejs.org to download and install node.js for your system. If you have npm installed and still getting this error message, set NPM_BIN_PATH variable in settings.py to match path of NPM executable in your system. Example: NPM_BIN_PATH = "/usr/local/bin/npm" I have added NPM_BIN_PATH = r"C:\Program Files\nodejs\npm.cmd" to settings.py, which is the path to it. I tried r"C:/Program Files/nodejs/npm.cmd", 'C:\\Program Files\\nodejs\\npm.cmd', and even PurePosixPath(PureWindowsPath(r"C:/Program Files/nodejs/npm.cmd")). None work. I get the path from entering where npm.cmd on the command line, and I have verified it by going to that directory. What might be the problem? -
django admin Interdependent validation of formsets
i have two inlines in admin models class AdminModel(admin.ModelAdmin): ... inlines = [inline1, inline2] class inline1(admin.TabularInline): form = inline1form model = inline1model class inline2(admin.TabularInline): form = inline2form model = inline2model class inline1form(forms.ModelForm): class Meta: model = inline1Edge fields = ("field1",) class inline2form(forms.ModelForm): class Meta: model = inline2Edge fields = ("field2",) now my task is to check if in two inline, if two fields have value (one in inline1 and another in inline2) then show error i have come with a solution where when creating formsets i am checking if field has vlaue then return answer ie modified custom method ` class AdminModel(admin.ModelAdmin): def _create_formsets(self, request, new_object, change): formsets, inline_instances = super()._create_formsets(request, new_object, change) if request.method == "POST": location_formset = None individual_formset_validated = all([formset.is_valid() for formset in formsets]) if not individual_formset_validated: return individual_formset_validated # custom check condition on formsets if check_fail: inline1formset.non_form_errors().extend( ["Please select values for only one field, field1 config or field2 config"] ) return formsets, inline_instances this is working fine, and adding error in the inline is there any other pythonic way which can help me solve this task ? -
Is it possible to use my own admin panel template created in html, bootstrap for django admin panel
I am new in django and in admin customization i want to know is it possible to use own admin panel created in html, bootstrap instead of django built in admin , or is there any other django admin templates which i can use as built in admin not looks good. i tried admin customization by overlapping the files but I think it is not the right thing is there any other solution , or i have to change the admin urls to my own admin template and have to do all the CRUD things by my own , as in django they are build in for models. -
Is it possible to translate paths (i18n, gettext_lazy) in RoutablePageMixin-Pages?
I have created a page with RoutablePageMixin and defined a child path. I want to translate this child path based on the active language with gettext_lazy like it works in Django within urlpatterns. I always get 404. Is this even possible or am I missing something? Here is my Page definition: class StudyBrowserPage(RoutablePageMixin, TranslatedPage): page_description = "Weiterleitung zum Studienbrowser" @path('') def list_studies(self, request): studies = Study.objects.all() return self.render(request, context_overrides={ 'studies': studies }) # here I actually want another parameter, but i tried to keep it simple. So don't mind the uselessness of the function. @path(_('studie') + '/') def study_detail_view(self, request): return self.render(request, template='wagtail_home/study_detail.html') I have translated the string in my django.po: msgid "studie" msgstr "study" Calling .../studie/ works. .../study/ does not. Edit: I think I have all the necessary settings in my config: "context_processors": 'django.template.context_processors.i18n', USE_I18N = True WAGTAIL_I18N_ENABLED = True I also have wagtail-localize installed. -
Django form dynamically created fields miss from cleaned_data
I'm trying to implement dynamic fields in ModelForm using AJAX requests. I have a cameras_num custom field as IntegerField. Once user picks value AJAX passes cameras_num field's value to ModelForm with kwargs and generates forms.ModelChoiceField with names camera_{number} ("camera_1", "camera_2" ... "camera_3"). However when form submits form.data contains all "cameras" (lets say {"camera_1": [1], "camera_2": [2]}) while form.cleaned_data contains only one camera ("camera_1"). class ConfigurationForm(forms.ModelForm): def __init__(self, *args, **kwargs): cameras_qty = kwargs.pop('cameras_qty', 1) super(ConfigurationForm, self).__init__(*args, **kwargs) if cameras_qty: for camera_num in range(1, cameras_qty+1): self.fields[f"camera_{camera_num}"] = forms.ModelChoiceField( label=f"Camera {camera_num}", queryset=models.Camera.objects.all() ) cameras_num = forms.IntegerField( widget=forms.Select(choices=[(i,i) for i in range(1, 4)]), initial=1 ) -
Different name of serializer data django
I want to serializer a list of dicts that contain a whitespace. Obviously I can't write cat name = serializer.Charfield(...) in Python (see the space between the and cat). So, I tried source=, but I get an error. { "cat_name": [ "This field is required." ] } Here's my code: class MySerializer(serializers.Serializer): cat_name = serializers.CharField(source='Cat name') s = MySerializer(data={'Cat name': 'Smith'}) s.is_valid(raise_exception=True) What am I doing wrong? Note that this can't change: data={'Cat name': 'Smith'} -
Stream data from Postgres to http request using Django StreamingHttpResponse
I would like to allow my users to download data from a Postgres DB, no matter the size of the requested data. For that reason, I would like to stream the data from the DB to the user. I have seen that StreamingHttpResponse is useful to stream an HTTP response and there is a snippet in the Django documentation that shows how to stream a large CSV file. I have also seen that psycopg2 has some streaming capabilities but I cannot find a way to "connect" the 2 streams. I have tried something along the lines of: class Echo: """An object that implements just the write method of the file-like interface. """ def write(self, value): """Write the value by returning it, instead of storing in a buffer.""" return value def stream(request): sql_query = sql.SQL( """ COPY (select * from table) TO STDOUT WITH CSV HEADER """) # create the file like object pseudo_buffer = Echo() # I would like data to flow from the DB to HTTP response with connection.cursor() as cursor: return StreamingHttpResponse(cursor.copy_expert(sql_query, pseudo_buffer), content_type="text/csv", headers={"Content-Disposition": 'attachment; filename="somefilename.csv"'},) I could make many small SQL requests and stream the data chunk by chunk using StreamingHttpResponse, but can I stream the … -
Disable stoping the container after stop debuging in Pycharm
I set up the debugging for my Django app that is inside the docker container in PyCharm. I did it with: a new interpreter via Docker Compose created the new run configuration Django Server. My settings are: Interpreter: new docker-compose interpreter host: 0.0.0.0 port: 8000 All work well (start docker container in the terminal, start debugger - it works) BUT: When I click the stop debugger, this stops my docker container. How to set it to not stop - so I can use it as a "normal" development container? (And that I don't need to restart it every time) -
I tried to implement disqus comments to my website made with django. But when someone tries to login disqus, loading never stops
So i implemented disqus comments to a new website of mine. When i tried to login my disqus account it said "please wait." and never logins until website refreshed. Code in website: <div id="disqus_thread" class="disqus-container"></div> code inside script MY_SRC is my src: <script> var disqus_config = function () { this.page.url = window.location.href; this.page.identifier = window.location.pathname; }; (function() { var d = document, s = d.createElement('script'); s.src = 'MY_SRC'; s.setAttribute('data-timestamp', +new Date()); (d.head || d.body).appendChild(s); })(); </script> I was expecting it to login immediately. It caused some confusion and my friends can not comment -
Is it possible to terminate an AI training process in django?
I am developing a webpage using Django. In the admin site, there is a section called: Train Model, in here, there is a button called "Train Model" this button runs a python script that has a simulation of a training process, it is just a sleep(30) for now, while the sleeping time is happening the user should be able no cancel this process, in case the user forgot something, is it possible to do so? I have tried some things, but the logs show that even if I press the cancel button, the "training" process runs until it is completed. import time import multiprocessing import os import signal import logging # Global variables to manage the training state is_training = False training_process = None training_pid = None # Store the PID of the training process stop_event = None logger = logging.getLogger() def train_task(stop_event): """simulates the training task with stop event support""" for i in range(30): if stop_event.is_set(): print("Training cancelled.") return time.sleep(1) print("Training done.") def train_model(): global is_training, training_process, stop_event # If training is already in progress, return immediately if is_training: print("Training already in progress...") return "Training already in progress" #mark the start of the training is_training = True stop_event = … -
Dynamic ChoiceField
I am on Django 5.1.1. I have a IngredientFormSet for IngredientForm(forms.Form). The form has a ChoiceField as shown in snippet below. The number of ingredients are a few thousand in IngredientModel. select2 has been used so that user can type in this field, and select2 filters the names using an Ajax call. Now, when I submit the form, I get error that the id of the ingredient name is not part of the choices (as choices=[]), which is expected, but obviously it doesn't work for my case. I want to update the IngredientForm.__init__(self, *args, **kwargs) such that whatever ingredient_id I get in the kwargs, I will get that exact value, do Ingredient.objects.get(id=ingredient_id), if a row is found, then add that single value in the choice, i.e. self.fields['ingredient'].choices = [(ingredient_id, ingredient_id)]. class IngredientForm(forms.Form): ingredient = forms.ChoiceField( label='Ingredient name', required=True, choices=[], ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) form_ingredient_id = ? # how to get hold of value of option here? if IngredientModel.objects.filter(id=form_ingredient_id).exists(): self.fields['ingredient'].choices = [(form_ingredient_id, form_ingredient_id)] So how do I get hold of the ingredient_id which select2 has put in the form choicefield? Note that when initializing the formset, I use custom prefix. -
Django Model Instances Not Displaying in Template
I'm having trouble displaying model instances in my Django template. I have created instances of my Tribute model, and they exist in the database. However, when I render my template, the model instances are not being displayed. Here’s a breakdown of my code: Model: from django.db import models from django.core.validators import URLValidator class Tribute(models.Model): card_styling = models.CharField(max_length=100, blank=True) tribute_title = models.CharField(max_length=100, blank=True) tribute_text1 = models.TextField(blank=True) tribute_text2 = models.TextField(blank=True) tribute_stripe_link1 = models.URLField(validators=[URLValidator], blank=True) tribute_stripe_link2 = models.URLField(validators=[URLValidator], blank=True) tribute_stripe_link3 = models.URLField(validators=[URLValidator], blank=True) tribute_stripe_link4 = models.URLField(validators=[URLValidator], blank=True) tribute_stripe_link5 = models.URLField(validators=[URLValidator], blank=True) tribute_stripe_link6 = models.URLField(validators=[URLValidator], blank=True) tribute_payment_button_class1 = models.CharField(max_length=100, blank=True) tribute_payment_button_class2 = models.CharField(max_length=100, blank=True) tribute_payment_button_class3 = models.CharField(max_length=100, blank=True) tribute_payment_button_class4 = models.CharField(max_length=100, blank=True) tribute_payment_button_class5 = models.CharField(max_length=100, blank=True) tribute_payment_button_class6 = models.CharField(max_length=100, blank=True) price1 = models.CharField(max_length=100, blank=True) price2 = models.CharField(max_length=100, blank=True) price3 = models.CharField(max_length=100, blank=True) price4 = models.CharField(max_length=100, blank=True) price5 = models.CharField(max_length=100, blank=True) price6 = models.CharField(max_length=100, blank=True) def __str__(self): return self.tribute_title or 'Unnamed Tribute' View: from django.shortcuts import render from .models import Tribute def tribute_view(request): # Get all Tribute objects tributes = Tribute.objects.all() # Pass the Tribute objects to the template context context = { 'tributes': tributes } return render(request, 'shop7/shop(with_models).html', context) Template {% extends 'shop7/base.html' %} {% load static %} {% block body %} <div class="container … -
Page not found Django restframework
Im trying to write an API in django to get the user comments from the url my API is : class ListSpecificUserCommentsApiView(APIView): authentication_classes = [authentication.TokenAuthentication] permission_classes = [permissions.AllowAny] def get(self, request: HttpRequest, user) -> Response: username: User = User.objects.get(id=user.id) comments: Comment = Comment.objects.filter(user=username) serialized_comments: CommentModelSerializer = CommentModelSerializer(instance=comments, many=True).data return Response(serialized_comments) and my urls.py : urlpatterns = [ path( route='users', view=views.ListUsersApiView.as_view(), name='users', ), path( route='comments/<user>', view=views.ListSpecificUserCommentsApiView.as_view(), name='user-comments', ), ] and still im facing this Page not found error I tried to pass the user as data in DRF Response like the code below: class ListSpecificUserCommentsApiView(APIView): authentication_classes = [authentication.TokenAuthentication] permission_classes = [permissions.AllowAny] def get(self, request: HttpRequest, user) -> Response: username: User = User.objects.get(id=user.id) comments: Comment = Comment.objects.filter(user=username) serialized_comments: CommentModelSerializer = CommentModelSerializer(instance=comments, many=True).data return Response(serialized_comments, data=user) but it didn't work -
Object of type ListSerializer is not JSON serializable
I want to Serialize a Django model and Show it as a DRF Response and Im facing this error many times here is my API view: class ListCommentsApiView(APIView): authentication_classes = [authentication.TokenAuthentication] permission_classes = [permissions.AllowAny] def get(self, request: HttpRequest) -> Response: comments = Comment.objects.all() serialized_comments = CommentModelSerializer(instance=comments, many=True) return Response(serialized_comments) here is my model: class Comment(models.Model): RATES: list[tuple[int, str]] = [ (1, 'Worst'), (2, 'Meh'), (3, 'Best'), ] user = models.ForeignKey(to=User, default=None, blank=True, on_delete=models.CASCADE ,verbose_name='User') text = models.TextField(max_length=200, default=None, blank=True, verbose_name='Comment') rate = models.IntegerField(choices=RATES, default=None, blank=True, verbose_name='Rate') viewed_by_admin = models.BooleanField(default=False, blank=True, verbose_name='Viewed By Admin') created_at = models.DateTimeField(auto_now_add=True, verbose_name='Created at') updated_at = models.DateTimeField(auto_now=True, verbose_name='Updated at') def __str__(self) -> str: return str(self.user) class Meta: verbose_name = 'Comment' verbose_name_plural = 'Comments' here is my serializer: from rest_framework import serializers from comment.models import Comment class CommentModelSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ['text', 'rate'] so I tried many things but it didn't work and I don't know what to do and I would appreciate a little help