Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How Can I Get Django Global Notifications Via Channels To Work?
I have spent the last month or so on and off trying to get the django channels notification to work. I can't get notifications to work but the chat works as expected. Here is my code... Consumers.py class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.is_group_chat = 'group_name' in self.scope['url_route']['kwargs'] if self.is_group_chat: group_name = self.scope['url_route']['kwargs'].get('group_name') self.group_name = group_name.replace('_', ' ') # Replace underscores with spaces try: self.group_chat = await database_sync_to_async(GroupChat.objects.get)(name=self.group_name) except GroupChat.DoesNotExist: await self.close() return self.chat_group = f'group_{self.group_name.replace(" ", "_")}' else: self.recipient_username = self.scope['url_route']['kwargs'].get('recipient_username') self.sender = self.scope['user'] self.conversation_group = self.get_conversation_group_name( self.sender.username, self.recipient_username ) # Convert recipient_username to a User object and assign it to self.recipient try: self.recipient = await database_sync_to_async(get_user_model().objects.get)(username=self.recipient_username) except get_user_model().DoesNotExist: await self.close() return # Join the group if self.is_group_chat: await self.channel_layer.group_add( self.chat_group, self.channel_name ) else: await self.channel_layer.group_add( self.conversation_group, self.channel_name ) await self.accept() def get_conversation_group_name(self, user1, user2): return f'chat_{sorted([user1, user2])[0]}_{sorted([user1, user2])[1]}' async def disconnect(self, close_code): if self.is_group_chat: await self.channel_layer.group_discard( self.chat_group, self.channel_name ) else: await self.channel_layer.group_discard( self.conversation_group, self.channel_name ) async def receive(self, text_data): text_data_json = json.loads(text_data) timestamp = timezone.now().isoformat() sender = self.scope['user'] sender_full_name = await self.get_user_full_name(sender) # Fetch full name message = text_data_json.get('message', '') attachment = text_data_json.get('attachment', None) message_type = text_data_json.get('type') # Ensure sender full name is calculated sender_full_name = await self.get_user_full_name(sender) if … -
exclude specific urls from nginx redirect
I'm trying to exclude two URLs from nginx redirect (http to https). Traffic from Nginx is sent to guincorn and the URLs are generated dynamically by the Django view. My current base nginx configuration for the site is below. All non http requests are sent to https using this. server { listen 80; listen [::]:80 default_server; server_name mydomain.org; return 301 https://$server_name$request_uri; } server { listen 443 ssl default_server; listen [::]:443 ssl default_server; ssl_certificate ....; ssl_certificate_key ....; root /app/ioc; server_name mydomain.org; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /path/static/; } location / { proxy_pass http://unix:/run/gunicorn.sock; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-For $remote_addr; proxy_redirect off; } } Now, I'm trying to exclude both this/endpoint1.txt and this/endpoint2.txt from the redirects. endpoint1.txt and endpoint1.txt are dynamically generated by the django view so they are not actual text files on the server. Trying to do something like this results in 404 error location /this/endpoint1.txt { root /path/app; add_header Content-Type text/plain; } Also, when I do something like this: location /this/endpoint1.txt { proxy_pass http://127.0.0.1:80; } I get 504 Gateway Time-out error. I'm binding gunicorn like this "0.0.0.0:8000" -
Best way to implement date with optional day/month?
There are several ways to do this, each with their own advantages and disadvantages. Boolean fields for day/month: Advantages: cheap ordering, easy formatting, easy validation Disadvantages: have to provide a default month/day, ordering may not behave as expected depending on needs date = models.DateField() date_has_month = models.BooleanField() date_has_day = models.BooleanField() Separate IntegerFields Advantages: relatively cheap ordering, flexible ordering with not_null option etc Disadvantages: complicates date validation, must order on several fields, must compose date from several fields date_year = models.IntegerField() date_month = models.IntegerField() date_day = models.IntegerField() CharField Advantages: no need for extra fields, 1:1 with user input (depending on validation) Disadvantages: relatively expensive ordering, ordering is inflexible, validation may be complicated date = models.CharField() My question is: are there more (dis)advantages not listed? Are there other ways to achieve this that I haven't thought of? -
backward lookup is not working in django 5.x
We are migrating our django app from django==3.2.25 to django==5.1.6. OneToOneField, ManyToManyField are giving errors on revers lookup. I have models as below. from django.db import models class Switch(models.Model): fqdn = models.CharField(max_length=45, unique=True) class Meta: managed = False db_table = 'Switch' app_label = 'myapp_models' class ConfigState(models.Model): switch = models.OneToOneField(Switch, models.CASCADE, db_column='switch', primary_key=True, related_name='config_state') class Meta: managed = False db_table = 'ConfigState' app_label = 'myapp_models' class EdgeSwitch(models.Model): switch = models.OneToOneField(Switch, models.CASCADE, db_column='switch', primary_key=True, related_name='edge_switch') class Meta: managed = False db_table = 'EdgeSwitch' app_label = 'myapp_models' When I try to get backward lookup query in DJango==3.X it works. >>> print(EdgeSwitch.objects.filter(switch__config_state=1).query) SELECT `EdgeSwitch`.`switch`, `EdgeSwitch`.`cluster`, `EdgeSwitch`.`sequence`, `EdgeSwitch`.`position`, `EdgeSwitch`.`role`, `EdgeSwitch`.`span`, `EdgeSwitch`.`loopback_v4`, `EdgeSwitch`.`loopback_v6` FROM `EdgeSwitch` INNER JOIN `Switch` ON (`EdgeSwitch`.`switch` = `Switch`.`id`) INNER JOIN `ConfigState` ON (`Switch`.`id` = `ConfigState`.`switch`) WHERE `ConfigState`.`switch` = 1 Same code gives error in DJango==5.X >>> print(EdgeSwitch.objects.filter(switch__config_state=1).query) Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/user/virtualenvs/app_corp_1.0.X/lib/python3.12/site-packages/django/db/models/manager.py", line 87, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/user/virtualenvs/app_corp_1.0.X/lib/python3.12/site-packages/django/db/models/query.py", line 1476, in filter return self._filter_or_exclude(False, args, kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/user/virtualenvs/app_corp_1.0.X/lib/python3.12/site-packages/django/db/models/query.py", line 1494, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, args, kwargs) File "/home/user/virtualenvs/app_corp_1.0.X/lib/python3.12/site-packages/django/db/models/query.py", line 1501, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "/home/user/virtualenvs/app_corp_1.0.X/lib/python3.12/site-packages/django/db/models/sql/query.py", line 1609, in add_q clause, _ = self._add_q(q_object, self.used_aliases) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/user/virtualenvs/app_corp_1.0.X/lib/python3.12/site-packages/django/db/models/sql/query.py", line … -
Django DRF showing weired auth methode respective to URL
I'm facing a strange issue with Django REST Framework (DRF). # views.py class CheckoutView(APIView): permission_classes = [AllowAny] def post(self, request, *args, **kwargs): return Response({'total_price': 7879}) #url.py urlpatterns = [ path("cart/checkout/<int:new>", checkoutView.as_view() , name="checkout"), # url 1 path("cart/checkout/", checkoutView.as_view() , name="checkout"), # url 2 ] issue : if i hit with url 1 it gives response 200 if i hit url 2 it gives response 401 { "detail": "Authentication credentials were not provided." } note that : 'permission_classes = [AllowAny]' is there in the view also i dont have defined default permission class in settings.py -
Django can't load static files, even with correct settings
Today i faced a problem with static files. I was adding JavaScript and CSS to my project, but the app could not load it. It did find the files, but could not load them, because the app shows 404 code (see picture). I made sure that i have these lines in my settings.py: STATIC_URL = 'static/' STATIC_ROOT = BASE_DIR / 'static' Then i made sure i ran collectstatic command and linked them in html template. <link rel="stylesheet" href="{% static 'css/style.css' %}"> <script src="{% static 'js/script.js' %}"></script> Anyway, i got 404 in console section of browser Google Chrome Console This is the second time i'm facing this problem. On my previous little project as wel, I encountered the same problem. I tried to find solution to this problem from every corner of internet: this site, django forum and other forums. But i could not find any solution. I have a thought that this problem may be with my laptop or OS maybe. My OS is Linux Ubuntu 22.04 LTS. If there is someone that encountered same problem or has any idea how to solve this problem, I would be glad. -
How to persist default class configurations in the database?
Let's say I've a ToDo model and Point model with foreign key relation in database. class Todo(ManuallyTimestampedModel): title = models.CharField(max_length=255) description = models.TextField() class Point(Model): title = models.CharField(max_length=255) description = models.TextField() todo = models.ForeignKey( Todo, on_delete=models.CASCADE, related_name="points", help_text=_("ToDo to which point belongs."), ) I also have a function for creating a few todos and points assigned to then based on chosen option: class PlanType(enum.Enum): RUNNING = "Running" SWIMMING = "Swimming" def plan(option: PlanType) -> None: todos = [] if option == PlanType.RUNNING: options = ... elif option == PlanType.SWIMMING: options = ... return todos What is a good approach to load default todos and points based on chosen option? I plan to store them in database with possibility to edit via admin UI. -
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 …