Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't see any results from Celery Beat in Django Project
I want to run scheduled tasks in my django backend with celery and celery beat. I have a Dockerfile config for both celery container beside the normal django container. I cant see any results from the execution. Does anyone have an idea? both with this config, just one with "worker" and one with "beat" in last line: # Use an official Python runtime as a parent image FROM python:3.11-slim ENV PYTHONUNBUFFERED 1 ENV APP_HOME=/usr/src/app # Set the working directory in the container WORKDIR /usr/src/app # Install Pip Packages RUN pip install --upgrade pip COPY server/requirements.txt $APP_HOME RUN pip install --no-cache-dir -r requirements.txt # Copy the rest of the application code into the container COPY server $APP_HOME # Define environment variable ENV DJANGO_SETTINGS_MODULE=musterteile_server.settings # Create a non-root user and change ownership of APP_HOME RUN addgroup --system appgroup && adduser --system --ingroup appgroup appuser && \ chown -R appuser:appgroup $APP_HOME # Switch to the non-root user USER appuser # Run Celery worker CMD ["celery", "-A", "musterteile_server.celery", "worker", "-E", "--loglevel=info"] musterteile_server/settings.py has the config for celery with a beat schedule for a test task. CELERY_BROKER_URL = os.environ.get("CELERY_BROKER_URL", "redis://localhost:6379/0") CELERY_RESULT_BACKEND = os.environ.get( "CELERY_RESULT_BACKEND", "redis://localhost:6379/0" ) CELERY_CONFIG_MODULE = os.environ.get( "CELERY_CONFIG_MODULE", "musterteile_server.celery" ) CELERY_TIMEZONE = os.getenv("TIME_ZONE", … -
setting acks_late=True doesnt re-execute the task if worker process is killed
i want to reproduce this behaviour highlighted in celery doc If the worker won’t shutdown after considerate time, for being stuck in an infinite-loop or similar, you can use the KILL signal to force terminate the worker: but be aware that currently executing tasks will be lost (i.e., unless the tasks have the acks_late option set). this is my task: @shared_task( name='CHECK_ACK', acks_late=True, ) def check_ack(): print('task picked') time.sleep(60) print('task completed after 60r seconds') here are steps i am following: 1.start celery: celery -A master worker --concurrency=2 2.run the task from django shell: check_ack.delay() 3. while task is running execute :pkill -9 -f 'master worker' 4. now restart celery again : celery -A master worker --concurrency=2 But i don't see the task getting re-picked by workers. What am i missing? -
Get data from views to a Javascipt file
In django, I'm trying to make a webapp where the the graph is defined in javascript and I want the data to come from firebase (the only way I know to get that data is in the views) how do I pass the data to it since what I only know is to pass that data to html I've tried using json response, but I dont know how to route the data to the static files where the javascript is located -
DJANGO + FIREBASE deployment with ssl certificate
I am currently deploying a django project that uses firebase_admin. at first when it was just deployed i can access it smoothly when it was just an ip provided by amazon aws. but when i used the bought ssl certificate and domain, after setting up everything, it now returns internal error 500 when i am trying to use from firebase_admin import messaging. but when i comment out everything about firebase, the website works. when i looked in the error logs it says no module _ssl i tried everything(i think). tried rebuilding python remaking virtualenv installing libssl almost everything that i saw on the internet while searching but nothing has worked yet in my django views.py when I do this import firebase_admin from firebase_admin import credentials it's fine like the site will work but when i do it like this import firebase_admin from firebase_admin import credentials, messaging i get this error in the apache2 error log [Thu Feb 13 08:52:34.813237 2025] [wsgi:error] [pid 1687181:tid 1687236] [remote xxx.xxx.x.xx:xxxxx] import ssl [Thu Feb 13 08:52:34.813243 2025] [wsgi:error] [pid 1687181:tid 1687236] [remote xxx.xxx.x.xx:xxxxx] File "/opt/bitnami/python/lib/python3.11/ssl.py", line 100, in <module> [Thu Feb 13 08:52:34.813246 2025] [wsgi:error] [pid 1687181:tid 1687236] [remote xxx.xxx.x.xx:xxxxx] import _ssl # if … -
A problem occurs when adding a new foreign key field to a model
So, I added a foreign key field to my model, ran "makemigrations" and "migrate" without problems, but when I check my database via DB browser, I cannot find that field! This is my model class Listing (models.Model): CATEGORY_CHOICES = [ ("chemistry", "Chemistry"), ("physics", "Physics"), ("math", "Math"), ("litreture", "Litreture"), ("history", "History"), ("language", "Language"), ("sports", "Sports") ] title = models.CharField(max_length=80) brief = models.CharField(max_length=128) description = models.TextField() intial_price = models.IntegerField() category = models.CharField(max_length=24, choices=CATEGORY_CHOICES) # The problem is within the line below creator = models.ForeignKey(User, on_delete=models.CASCADE, related_name='listings') # I cannot find this field in my database file when browsing it via DB browser def __str__(self): return self.title I tried to ask the AI a lot but all it said was to check the migrations files and make sure the migration process is successful. I am sure that there is no issue with those two. I ran out of ideas, help! -
Best place to initialize a variable from a postgres database table after django project startup
I have a django project where I have some database tables. One of the database tables is designed to store messages and their titles. This helps me to create/alter these messages from my django-admin. Now I want to initialize a variable (as a dictionary) from this table as follows : MY_MSGS = {record.name : {'title':record.title, 'message':record.message} for record in MyTable.objects.all()} This must happen at the server startup for now. MY_MSGS must be accessible to the different view-files. FYI I have multiple view-files that are all imported from views.py -
Django API JSONfield fetches an object that I can't use .map to parse and then build a chart
I have a Django serialized API field that contains database JSONfield data that creates a chart (this data is confirmed to work on my Flask backend), but I can't use the same data taken from a Django API ''' // data.data.linechart: "[{'index': 1295395200000, 'Strategy': 28.8935858208}, {'index': 1304035200000, 'Strategy': 33.3317284202}]" fetch(url) .then(response => response.json()) .then(data => { var dataArray = Object.keys(data.data.linechart).map(function(key) { return [key, data.data.linechart[key]]; }); // Convert the array of key-value pairs to a format that supports map var mapData = dataArray.map(function(item) { return { index: item[0], Strategy: item[1] }; }); const series = [ { name: 'Strategy', data: mapData } ]; //Apex Chart var optionsChart = { series: [{ name: 'New Data', data: series }], What am I missing here? Fetch is pulling serialized API data as an object - and the conversion above isn't working. Have others seen the same problem? I have tried: JSON.parse(data), JSON.stringify(data), Stripping brackets: const dataArray = data2.data.linechart.replace('[', '').replace(']', ''); but I cannot convert the chart data JSON from an Object - without splitting the JSON string into individual characters... -
Logout, Clear Cache, and Prevent Back Navigation to Previous Window
Currently, I have a few view that is called unlogin and login: views.py @cache_control(no_cache = True, must_revalidate = True, no_store= True) def unlogin(request): logout(request) response = redirect('main') response['Cache-Control'] = 'no-cache, no-store, must-revalidate' response['Pragma'] = 'no-cache' response['Expires'] = 0 return response def login(request) form = formfill() # User fills form and processing user = authenticate(request, username=username, password=password) if user: login(request, user=user) return redirect('signedinpage') return render(request, 'myloginpage.html', {'form1': form}) def success(request): # Process logout return render(request,'signinginpagecomplete.html') On urls.py I have: urlpatterns = [ path('unlogin/',view=views.unlogin, name="unlogin"), path('mylogin/', view=views.login, name="mylogin"), path="signedinpage/" views=view.success, name="signedinpage"] I am expecting that when I press the logout button that is in success view, I will logout the user and the user will not be able to go back to the previous page. -
ModuleNotFoundError attempting to load development settings
I'm very new to Django, so please excuse my rookie question. I understand the need to separate the development configuration from the production one. And so I have created a folder at br_project/br_project/settings/ and in it I have these files: - __init__.py - base.py - development.py - production.py The br_project/br_project/__init__.py file contains: import os env = os.environ.get('DJANGO_ENV', 'local') if env == 'production': from .production import * else: from .development import * When .development is called, I get an error: ModuleNotFoundError: No module named 'br_project.production' Somehow my configuration files are not being found. What have I set up wrong? -
KeyError: 'admin' even when admin is under installed apps
I am getting an error that I am having trouble fixing. When I try to run the server or makemigrations to migrate it says the admin app is not there. However I have checked the installed apps under the settings file and it is there. I don't understand why I am getting this error. INSTALLED_APPS = [ # Django Apps 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', (env) PS C:\Users\inr69\Documents\GitHub\afreebird_website_3.0> python manage.py makemigrations C:\Users\inr69\Documents\GitHub\afreebird_website_3.0\config\settings C:\Users\inr69\Documents\GitHub\afreebird_website_3.0 LOADING: C:\Users\inr69\Documents\GitHub\afreebird_website_3.0\.env ENV FILE LOADED Traceback (most recent call last): File "C:\Users\inr69\Documents\GitHub\afreebird_website_3.0\env\Lib\site-packages\django\apps\registry.py", line 158, in get_app_config return self.app_configs[app_label] ~~~~~~~~~~~~~~~~^^^^^^^^^^^ KeyError: 'admin' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\inr69\Documents\GitHub\afreebird_website_3.0\manage.py", line 17, in <module> execute_from_command_line(sys.argv) File "C:\Users\inr69\Documents\GitHub\afreebird_website_3.0\env\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\inr69\Documents\GitHub\afreebird_website_3.0\env\Lib\site-packages\django\core\management\__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\inr69\Documents\GitHub\afreebird_website_3.0\env\Lib\site-packages\django\core\management\base.py", line 413, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\inr69\Documents\GitHub\afreebird_website_3.0\env\Lib\site-packages\django\core\management\base.py", line 454, in execute self.check() File "C:\Users\inr69\Documents\GitHub\afreebird_website_3.0\env\Lib\site-packages\django\core\management\base.py", line 486, in check all_issues = checks.run_checks( ^^^^^^^^^^^^^^^^^^ File "C:\Users\inr69\Documents\GitHub\afreebird_website_3.0\env\Lib\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\inr69\Documents\GitHub\afreebird_website_3.0\env\Lib\site-packages\django\core\checks\urls.py", line 136, in check_custom_error_handlers handler = resolver.resolve_error_handler(status_code) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\inr69\Documents\GitHub\afreebird_website_3.0\env\Lib\site-packages\django\urls\resolvers.py", line 732, in resolve_error_handler callback = getattr(self.urlconf_module, "handler%s" % view_type, None) ^^^^^^^^^^^^^^^^^^^ File "C:\Users\inr69\Documents\GitHub\afreebird_website_3.0\env\Lib\site-packages\django\utils\functional.py", line 47, in __get__ res = instance.__dict__[self.name] … -
Unable to retrieve Authjs (NextAuth 5) access token server-side in Next.js 15 with Django backend
I'm trying to set up authentication in my Next.js application using NextAuth.js with a Django backend. As Oauth provider i'm use django-oauth-toolkit. The goal is to pass the access token in the Authorization header when making requests to the Django API. I have successfully set up the OAuth2 provider in Auth.js, and I'm able to log in through the Django authentication system. However, when I try to retrieve the access token server-side in my Next.js app (in a server component), I am unable to find it. I try to follow the official tutorial for thirdy parts backends: https://github.com/nextauthjs/next-auth-example I'm using NextJS 15.1.7 and Authjs (NextAuth.js v5) Here’s the relevant code: src\auth.ts import NextAuth from "next-auth" import "next-auth/jwt" declare module "next-auth" { interface Session { accessToken?: string } } declare module "next-auth/jwt" { interface JWT { accessToken?: string } } const DJANGO_URL = process.env.NEXT_PUBLIC_DJANGO_URL; const NEXTJS_URL = process.env.NEXT_PUBLIC_NEXTJS_URL; export const { handlers, auth, signIn, signOut } = NextAuth({ providers: [{ id: "django", // signIn("my-provider") and will be part of the callback URL name: "Django", // optional, used on the default login page as the button text. type: "oauth", // or "oauth" for OAuth 2 providers userinfo: `${DJANGO_URL}/api/o/userinfo/`, token: `${DJANGO_URL}/api/o/token/`, wellKnown: `${DJANGO_URL}/api/o/.well-known/openid-configuration/`, … -
django-allauth MFA cannot add Webauthn security key
Im trying to setup django-allauth's MFA for my system and successfully got the authenticator app to work. I am using the default templates and when I tried adding a security key, it is not working and outputs "(Hidden field credential) This field is required." in the form. here is my settings.py setup: ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = False ACCOUNT_EMAIL_VERIFICATION_BY_CODE_ENABLED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATED_LOGIN_REDIRECTS = False MFA_ADAPTER = "allauth.mfa.adapter.DefaultMFAAdapter" MFA_PASSKEY_SIGNUP_ENABLED = True MFA_SUPPORTED_TYPES = ["recovery_codes", "totp", "webauthn"] MFA_WEBAUTHN_ALLOW_INSECURE_ORIGIN = True MFA_PASSKEY_LOGIN_ENABLED = True -
if condition with field value don't work in Django template
In models I have: class Book(models.Model): status = models.ForeignKey( 'BookStatus', verbose_name='Status', on_delete=models.RESTRICT, null=True, blank=True, ) and class BookStatus(models.Model): name = models.CharField( max_length=50, unique=True, ) def __str__(self): """String for representing the Model object.""" return self.name In views I have a normal Model DetailView: class BookDetailView(LoginRequiredMixin, generic.DetailView): login_url = '/accounts/login/' model = Book In the template for this detail view I want to display a button only, if book.status is not "vorhanden". I try with this: {% if book.status != 'vorhanden' %} ... {% endif %} but this is also true, if the displayed book has status = vorhanden. I tried the reverse: {% if book.status == 'vorhanden' %} ... {% endif %} but this is not true, even if the displayed book has status = vorhanden What is my mistake? Thanks in advance Matthias -
Get table changes details without using triggers in postgres
I am working on a live dashboard which records changes in database and shows details related to it on the dashboard. Currently to get these live changes I am using a combination of triggers, functions and pg_notify to generate notifications from postgres when some tables have CRUD operations in them. All of this is working okay for now, but based on some suggestions I read online many people do not recommend to use triggers if it is possible, as they are hard to maintain and don't sit best with rest of our code base. So for this reason I want to try updating my trigger based approach with something which fits with my code better and easier to maintain. But I don't know what I can use instead of triggers to get live changes from database. Most triggers in my database are just used to send postgres notification back to my backend where I am handling the changes directly, so if I can get the changes from the database without using triggers I think I can make it work, but I can't figure out how to do so. Also, if you think that trigger based approach is better for my … -
How to fix CSRFToken headers and CORS issues in React + Django website
I have an application running with react as the frontend and django as the backend. When I use an online hosting service, I get the following issues: TypeError: NetworkError when attempting to fetch resource. AuthContext.js:37:14 Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost/\_allauth/browser/v1/auth/session. (Reason: header ‘x-csrftoken’ is not allowed according to header ‘Access-Control-Allow-Headers’ from CORS preflight response). Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost/\_allauth/browser/v1/auth/session. (Reason: CORS request did not succeed). Status code: (null). and, Access to fetch at 'http://localhost/_allauth/browser/v1/auth/session' from origin 'https://privatevoti.vercel.app' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.Understand this errorAI allauth.js:128 GET http://localhost/_allauth/browser/v1/auth/session net::ERR_FAILED f @ allauth.js:128 (anonymous) @ allauth.js:259 (anonymous) @ AuthContext.js:32 rs @ react-dom.production.min.js:243 ku @ react-dom.production.min.js:285 (anonymous) @ react-dom.production.min.js:281 k @ scheduler.production.min.js:13 R @ scheduler.production.min.js:14Understand this errorAI AuthContext.js:33 TypeError: Failed to fetch at f (allauth.js:128:22) at allauth.js:259:16 at AuthContext.js:32:5 at rs (react-dom.production.min.js:243:332) at ku (react-dom.production.min.js:285:111) at react-dom.production.min.js:281:391 at k (scheduler.production.min.js:13:203) at MessagePort.R (scheduler.production.min.js:14:128) (anonymous) @ AuthContext.js:33 Promise.catch (anonymous) @ AuthContext.js:32 rs @ react-dom.production.min.js:243 … -
Buffer channels when there are no consumers
When a channel has no consumers, can I get django to buffer all the messages sent on the channel instead, then after a consumer subscribes can I get it to send all the buffered messages again (to that consumer)? I think I can do it manually with very ugly solutions, involving four global variables and bespoke consumers, but does django provide an easier way to do it? -
Django Bokeh Stacked Bar Chart
I have the following queryset: <QuerySet [ {'Order_Type': 'Phone', 'Order_Priority': 'NA', 'Order_total': 2}, {'Order_Type': 'Web', 'Order_Priority': 'High', 'Order_total': 3}, {'Order_Type': 'Web', 'Order_Priority': 'Med', 'Order_total': 9}]> I want to create a stacked bar chart using Bokeh that shows the total number of orders for each order type; each bar will also show the breakdown order priority (see image). enter image description here I'm getting an error because the axis categorical factors (Order Type in this case) is not unique. can someone help me with this? -
How to log all errors related to an API request in Django Rest Framework along with multiple fields in a CSV file?
I want to log any type of error that occurs during an API request in Django Rest Framework into a CSV file, including the error message along with additional details like username, user ip, url, etc. I also want to capture errors that occur before reaching the view (e.g., errors related to JWT). I tried using middleware for this, but the issue was that some responses were not rendered correctly, and even after manually rendering, they still resulted in errors. I would appreciate it if you could suggest a solution. The code below is the middleware I tried to use. I don't have an issue with logging errors that occur inside the view because if I only wanted to log errors within the view, I could use decorators or create a custom APIView. However, what I'm looking for is a way to log any type of error, even those that occur outside the view. class ErrorLogMiddleware: def __init__(self, get_response): self.get_response = get_response self.filename = settings.ERROR_LOG_PATH self.fieldnames = ["Username", "IP", "User Agent", "Date/Time", "Time Interval", "Query", "Message", "URL"] def __call__(self, request): if not exists(self.filename): with open(self.filename, "a", newline="", encoding="utf-8") as csvfile: writer = DictWriter(csvfile, fieldnames=self.fieldnames) writer.writeheader() before = time() try: response … -
How to add a function result from a model to a list?
How to add a function result from a model to a list 'subdom()' models.py class Hromady(models.Model): ... def subdom(self): if self.alias: sub = self.alias else: sub = self.code.lower() return sub views.py def index(request): hromads = Hromady.objects.all() for hr in hromads: print(hr.subdom()) # ok hrom = hromads.annotate(obj_count=Count('object', filter=Q(object__state=1))) map_hrom = list(hrom.values('region', 'district', 'locality', 'type', *****subdom()*****???, 'obj_count')) -
Django re_path to catch all URLs except /admin/ not working properly
I'm trying to define a re_path in Django that catches all URLs except those that start with /admin/. My goal is to redirect unknown URLs to a custom view (RedirectView), while ensuring that all admin URLs (including subpaths like /admin/mymodel/something/) are excluded. from django.urls import re_path, path from django.contrib import admin from . import views urlpatterns = [ path('admin/', admin.site.urls), # Ensure Django admin URLs are handled ] # Catch-all pattern that should exclude /admin/ URLs urlpatterns += [ re_path(r"^.*/(?!admin/$)[^/]+/$", views.RedirectView.as_view(), name="my-view"), ] Issue: URLs like localhost:8000/admin/mymodel/something/ are correctly ignored, which is good. However, single-segment URLs like localhost:8000/something/ are not being matched, even though they should be redirected. -
Django 5 translate route with param
I have troubles to translate properly a route that needs a param. this works fine if the uri has /fr/ or /en/: urlpatterns = [ path(_('CATEGORY'), views.category, name='app-category'), ] But as long as I need to add a param like: urlpatterns = [ path(f"{_('CATEGORY')}/<slug:uuid>", views.category, name='app-category'), ] or urlpatterns = [ path(_('CATEGORY') + "/<slug:uuid>", views.category, name='app-category'), ] The translation stuck with 'category' so the route /fr/categorie/ is not working. _('CATEGORY') = 'categorie' for fr or 'category' for en. Any idea about how to bypass the issue? Thanks -
How to reset specific container child tags from tailwind styles
I am using tailwindcss in django project. Tailwind css by default reset all tags default styles. I am creating a blog page. The blog content is created with ckeditor. I am using {{content|safe}} to load the content as html. The issue arise here. The content default tag styles are not showing so the content is not showing as expected. I have tried with row css to unset the tailwind resets. .reset-default * { all: unset; box-sizing: border-box; } .reset-default p, .reset-default a, .reset-default button { all: unset; } .reset-default a { text-decoration: initial; color: initial; } .reset-default button { background: initial; border: initial; } .btn-custom { padding: 10px 20px; background-color: #3490dc; color: white; border-radius: 5px; } But it didn't work, so I tried with a tailwind css plugin, @tailwindcss/typography. I added prose class in the parent and the styles are added. But for the newlines it also taking margins for blank lines. Is there any way to reset the tags to default. -
Traceback not provided after upgrading to Django 5
I upgraded my django 4.1 to django 5.1.3, and sometimes the admin error emails are coming without traceback. Here is part of the email: Internal Server Error: /go Report at /go Internal Server Error: /go Request Method: GET Request URL: https://[domain]/whatever Django Version: 5.1.3 Python Executable: /usr/local/bin/python3.11 Python Version: 3.11.10 Python Path: ['/app', '/app', '/usr/local/bin', '/usr/local/lib/python311.zip', '/usr/local/lib/python3.11', '/usr/local/lib/python3.11/lib-dynload', '/usr/local/lib/python3.11/site-packages'] Server time: Tue, 11 Feb 2025 08:04:21 -0500 Installed Applications: [long list] Traceback (most recent call last): None Request information: USER: demo GET: POST: No POST data FILES: No FILES data The server doesnt show anything special, just a Internal Server Error. Memory is good and cpu also. -
ModuleNotFoundError: No module named ‘mysite’
I’m working on a python virtual environment: Python 3.13.1 Django 5.1.6 At this moment without apps, just the project. I’m trying to start the project with “runserver”, or I try to run makemigrations, or I try to run migrate, and I get this message: ModuleNotFoundError: No module named ‘mysite’ I’ve searched in my settings file, even in wsgi file and I see everything well. I’ve searched on Internet a lot of forums without success. I changed Django version, without success, the same message. I’ve created a lot of projects and I get this message for first time. I checked if there is something with "mysite" declared. -
Can we make a python script that can detect and identify person height weight from an image?
I tried someones Git but the results are not that good as the sample images provided by him is also not giving accurate results. I want a script in python that takes an image path, scan that image and look for a person in that image, gives back height and weight of person. I know that can't be 100% accurate but it should be 90+ correct. Input - Sample Image Output - Height: 117.8 cm, Weight: 68.6 kg Input - Sample Image2 Output - Height: 170.8 cm, Weight: 77.12 kg