Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Javascript fetching code instead of name within Django
This is a javascript that I have found in github, this is the link for it the problem is that when I used the ph-address-selector.js, it works but instead of fetching the "display name", it fetches the "code ids", which is the true value of the input when I ask ChatGPT about it. Also you can see the same issue from some user. so I tried the modified javascript code so that it will use the same url I used to connect it to my base.html, which extends all of my scripts to all of my html templates. ph-address-selector.js var my_handlers = { // fill province fill_provinces: function() { var region_code = $(this).val(); var region_text = $(this).find("option:selected").text(); $('#region-text').val(region_text); $('#province-text').val(''); $('#city-text').val(''); $('#barangay-text').val(''); let dropdown = $('#province'); dropdown.empty().append('<option selected="true" disabled>Choose State/Province</option>'); let city = $('#city'); city.empty().append('<option selected="true" disabled></option>'); let barangay = $('#barangay'); barangay.empty().append('<option selected="true" disabled></option>'); $.getJSON(provinceUrl, function(data) { var result = data.filter(value => value.region_code == region_code); result.sort((a, b) => a.province_name.localeCompare(b.province_name)); $.each(result, function(key, entry) { dropdown.append($('<option></option>').attr('value', entry.province_code).text(entry.province_name)); }); }); }, // fill city fill_cities: function() { var province_code = $(this).val(); var province_text = $(this).find("option:selected").text(); $('#province-text').val(province_text); $('#city-text').val(''); $('#barangay-text').val(''); let dropdown = $('#city'); dropdown.empty().append('<option selected="true" disabled>Choose city/municipality</option>'); let barangay = $('#barangay'); barangay.empty().append('<option selected="true" disabled></option>'); $.getJSON(cityUrl, … -
Celery + RabbitMQ random Connection reset by peer
I'm using celery in django with rabbitmq, it works fine but some times it gives ConnectionResetError traceback: [2024-09-18 07:08:31,427: ERROR/MainProcess] Error cleaning up after event loop: RecoverableConnectionError(None, 'Socket was disconnected', None, '') Traceback (most recent call last): File "/usr/local/lib/python3.11/site-packages/celery/worker/loops.py", line 97, in asynloop next(loop) File "/usr/local/lib/python3.11/site-packages/kombu/asynchronous/hub.py", line 306, in create_loop item() File "/usr/local/lib/python3.11/site-packages/vine/promises.py", line 161, in __call__ return self.throw() ^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/vine/promises.py", line 158, in __call__ retval = fun(*final_args, **final_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/kombu/transport/base.py", line 230, in _read drain_events(timeout=0) File "/usr/local/lib/python3.11/site-packages/amqp/connection.py", line 526, in drain_events while not self.blocking_read(timeout): ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/amqp/connection.py", line 531, in blocking_read frame = self.transport.read_frame() ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/amqp/transport.py", line 312, in read_frame payload = read(size) ^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/amqp/transport.py", line 629, in _read s = recv(n - len(rbuf)) ^^^^^^^^^^^^^^^^^^^ ConnectionResetError: [Errno 104] Connection reset by peer when checking rabbitmq logs (172.21.0.1:50078 -> 172.21.0.2:5672): user 'test' authenticated and granted access to vhost '/' rabbitmq-1 | 2024-09-19 07:43:51.816951+00:00 [error] <0.43132.0> closing AMQP connection <0.43132.0> (172.21.0.1:50072 -> 172.21.0.2:5672): rabbitmq-1 | 2024-09-19 07:43:51.816951+00:00 [error] <0.43132.0> missed heartbeats from client, timeout: 60s rabbitmq-1 | 2024-09-19 07:45:10.121070+00:00 [notice] <0.86.0> alarm_handler: {set,{system_memory_high_watermark,[]}} rabbitmq-1 | 2024-09-19 07:46:30.182591+00:00 [info] <0.43323.0> accepting AMQP connection <0.43323.0> (172.21.0.1:45394 -> 172.21.0.2:5672) rabbitmq-1 | 2024-09-19 07:46:30.183948+00:00 [info] <0.43323.0> connection <0.43323.0> (172.21.0.1:45394 -> 172.21.0.2:5672): … -
Django: using older version of postgresql
I want to develop a backend with Django and interact with a production database that runs PostgreSQL 12.X. Django 5, however, is only compatible with PostgreSQL 13+. There are the options of writing direct SQL commands hacking Django to overwrite the version check downgrade Django by two major versions, but I'm not happy with either of the solutions. Is there a more elegant way of using PostgreSQL 12 with Django 5? -
Am I using return render(request, url) wrong in django? (CS50)
In Project 1 of Web Development with Python and Javascript with CS50, I made a form class that should create a new wiki page. It's supposed to get the input before using its "action" to trigger a function which will return to the home page from the addpage page once it's done. But using return render() to send the input and other necessary information while redirecting to the home page (something that has worked fine in other functions) doesn't seem to work this time. There's a brief reload and the input just disappears, there's no redirect, and the util.save_entry() hasn't created a new page. Could someone give me a hint where I might've went wrong please? Thanks. The page for adding new pages {% extends "encyclopedia/layout.html" %} {% block title %} Encyclopedia {% endblock %} {%block head%} <link rel="stylesheet" href="styles.css"> {%endblock%} {% block body %} <h1>New Page</h1> <div class="formwrapper"> <form action = "{% url 'addpage' %}" method="post"> {% csrf_token %} {{title}} <input type="submit"> </form> </div> {% endblock %} My urls: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("<str:page>", views.getpage, name="page"), path("addpage", views.addpage, name="addpage") ] addpage function in views: def addpage(request): if request.method=="POST": title=NewTitle(request.POST) … -
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 = …