Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Read data json in django
I am currently working on a project where users will be able to authenticate themselves thanks to a form that I protected with a csrf token, but for now I only take care of the server side party, here is the code: @api_view(['POST']) @csrf_protect @permission_classes([AllowAny]) def login(request): if request.method != "POST": return JsonResponse({"error": "Seules les requêtes POST sont autorisées."}, status=status.HTTP_405_METHOD_NOT_ALLOWED) try: # Lecture sécurisée des données data = json.loads(request.body) username = data.get("username") password = data.get("password") if not username or not password: return JsonResponse({"error": "Nom d'utilisateur et mot de passe sont requis."}, status=status.HTTP_400_BAD_REQUEST) # Recherche de l'utilisateur dans les deux tables user = None role = None try: user = Administrateur.objects.get(username=username) role = "admin" except Administrateur.DoesNotExist: pass if not user: try: user = Employes.objects.get(username=username) role = "employe" except Employes.DoesNotExist: pass if not user or not check_password(password, user.password): return JsonResponse({"error": "Identifiants incorrects."}, status=status.HTTP_401_UNAUTHORIZED) # Génération des tokens refresh = RefreshToken.for_user(user) # Réponse sécurisée response = JsonResponse({"username": user.username}) # Stocker le JWT dans un cookie HttpOnly sécurisé response.set_cookie( key='access_token', value=str(refresh.access_token), httponly=True, secure=True, samesite='Strict', max_age=3600 ) # Stocker le rôle pour le frontend response.set_cookie( key='user_role', value=role, httponly=False, secure=True, samesite='Strict', max_age=3600 ) return response except Exception as e: return JsonResponse({"error": f"Erreur inattendue : {str(e)}"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) … -
Why I am getting htmx:targetError when calling form.requestSubmit?
I am using htmx to load some content when openning an accordion in my django template. I initially include the cover card partial template and when I close the accordion I remove the whole partial template. Then whenever the accordion opens I dispatch a custom event to trigger the htmx swap and return the same partial template in the response. The code looks like this initially: ... <details open id="cover-card-section" hx-get="{% url 'update-cover-card' object.id %}" hx-swap="outerHTML" hx-target="#temp-cover-card-form" hx-trigger="open-cover-card-section"> <summary > Cover Card </summary> {% include "path/to/cover_card.html" %} {% comment %} Element to be replaced by actual cover card form {% endcomment %} <div id="temp-cover-card-form" style="display: none; align-items: center; justify-content: center; width: 100%; height: 200px;"> <svg width="40" height="40" stroke="rgba(0, 0, 0, 0.5)" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><style>.spinner_V8m1{transform-origin:center;animation:spinner_zKoa 2s linear infinite}.spinner_V8m1 circle{stroke-linecap:round;animation:spinner_YpZS 1.5s ease-in-out infinite}@keyframes spinner_zKoa{100%{transform:rotate(360deg)}}@keyframes spinner_YpZS{0%{stroke-dasharray:0 150;stroke-dashoffset:0}47.5%{stroke-dasharray:42 150;stroke-dashoffset:-16}95%,100%{stroke-dasharray:42 150;stroke-dashoffset:-59}}</style><g class="spinner_V8m1"><circle cx="12" cy="12" r="9.5" fill="none" stroke-width="3"></circle></g></svg> </div> </details> ... The cover card partial template looks like this: <div class="container" id="cover-card-form-container" style="max-width:700px;" puny-settings> <style> ... </style> <div> <form id='image-upload-form' hx-swap="none" hx-encoding='multipart/form-data' hx-post='/en/home/upload-card-image/'> {% csrf_token %} {{ form.image.errors }} {{ form.image.label_tag }} {{ form.image }} <div style="display: none; width: 100%; align-items: center; gap: 8px; margin-bottom: var(--pico-spacing)" id="progress-container"> <progress style="width: 50%; margin-bottom: 0" id="progress-bar" value="0" … -
How to make the function stop immediately, when in websocket stop requested?
I want to stop running the generating function immediately, whenever stop_requested in the websocket. class ImageGeneration(BaseAIGeneration): async def process(self, websocket, prompt): if websocket.stop_requested: return None await super().process(websocket, prompt) if websocket.stop_requested: return None response = await self.generate_image(prompt=prompt, model=self.model, size=size) if websocket_instance.stop_requested or not response: return None if response and isinstance(response, list): image_url = response[0].url return image_url And generate_image function currently is synchronous function async def generate_image( prompt: str, model: str, size: str = "1024x1024" ): response = await client.images.generate( model=model, prompt=prompt, size=size, n=1 ) return response.data Currently it waits until generate_image fully runs, and only then stops. I was thinking of creating a task, that will gonna check if the response: while not task.done(): if websocket_instance.stop_requested: task.cancel() await asyncio.sleep(0.1) But for me this solution looks weird, and I do not think it is the correct way, how to make the function stop immediately, when in websocket stop requested? -
Deploying Django API with Render keeps loging 400 bad request
I am trying to host my Django API with renders free tier I have specified all the env variables including renders domain in allowed origins but I still get 400 Bad Request responses from renders logs. logs: 127.0.0.1 - - [24/Feb/2025:22:47:56 +0300] "HEAD / HTTP/1.1" 400 143 "-" "Go-http-client/1.1" ==> Your service is live 🎉 127.0.0.1 - - [24/Feb/2025:22:48:09 +0300] "GET / HTTP/1.1" 400 143 "-" "Go-http-client/2.0" my settings.py ALLOWED_HOSTS = env.list("ALLOWED_HOSTS") CSRF_TRUSTED_ORIGINS = env.list("TRUSTED_ORIGINS") CORS_ALLOWED_ORIGINS = env.list("CORS_ALLOWED_ORIGINS") all env variables are supplied on renders environment tab but it still fails -
Django/Celery SQLite database locked on concurrent access
I have a local Django 5.1/Celery 5.4 project that is using SQLite. I am the only user. Certain model saves trigger a Celery task that queries (SELECT) for the updated record (using the Django ORM), then runs an API call to update a remote record based on the local data, and then runs another UPDATE locally. The task wraps all this inside of with transaction.atomic():. (The Celery worker is configured to run tasks in serial.) While this task is running, any attempts to write to the database result in a "database is locked" OperationalError. I have configured Django/SQLite with the latest "production-ready" settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': DB_DIR / 'db.sqlite3', 'OPTIONS': { 'init_command': """ PRAGMA foreign_keys=ON; PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL; PRAGMA busy_timeout = 5000; PRAGMA temp_store = MEMORY; PRAGMA mmap_size=134217728; PRAGMA journal_size_limit=67108864; PRAGMA cache_size=2000; """, 'transaction_mode': 'IMMEDIATE', 'timeout': 20, }, }, } I was under the impression that with these settings, concurrent access was possible. "SQLite in Production" is the latest hotness, and these settings, especially the new-to-Django 5.1 'transaction_mode': 'IMMEDIATE' in OPTIONS, would allow writes to queue. What am I missing? -
dynamically instantiate database django
In a django web application, when logging in I am saving the name of the database in the session. I need a method to dynamically instantiate the database using this name that is saved in the user session. I dont't want to use "using()" because my aplication is already done, and it would give me a lot of work, neither by configuring multiple databases in your settings (because my databases are being createded dinamically) if there is another way i would like to know. Maybe it's not possible, i understand if it's the case... I tried middlewares, routes, threading, decorators but maybe a think i would have done something wrong. I exhausted my attempts. As far as I could go i get logged in the right database until the second screen of my application, when i am browsing in the application the 3 screen i pass the database goes back to default. middleware: import re from django.utils.deprecation import MiddlewareMixin from django.db import connections from .thread import set_banco_academia class DatabaseMiddleware(MiddlewareMixin): def process_request(self, request): """ Middleware que define dinamicamente o banco de dados a ser usado com base na sessão do usuário e adiciona a conexão ao Django. """ if not hasattr(request, … -
Django form doesn`t appear in page
I want to add posts in adding system from user profile page (without creating another page to adding). To profile page including html file for creating post I created model, form, view and html but have no idea why it isn`t working. The form doesn`t appear in page (except bottom "publish") include is working forms from django import forms from .models import Post, Comment class PostForm(forms.ModelForm): class Meta: model = Post fields = ['text', 'photo', 'video'] views from django.shortcuts import redirect, render from .models import Post, Comment from .forms import PostForm, CommentForm # Create your views here. from django.contrib.auth.decorators import login_required from django.views.decorators.http import require_GET, require_POST @login_required(login_url='users:login') def create_post(request): if request.method == 'POST': form = PostForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() return redirect('user:profile') else: form = PostForm() context = {'form': form} return render(request, 'post/create_post.html', context) create_post.html <div class="posts-section"> <div class="new-post"> <form method='post' enctype="multipart/form-data"> {{form.as_p}} {% csrf_token %} <button>Publish</button> </form> </div> </div> user_profile.html {% extends "base.html" %} {% load profile_tags %} {% block content %} </div> <div class="profile-info"> <p><strong>Email:</strong> {{ user.email }} </p> <p><strong>About:</strong>{{ profile.about }}</p> </div> {% include "post/create_post.html" %} </div> {% endblock content %} -
Is there any way to take add tooltip to the select2 li items?
i work on a django project where i also use bootstrap and select2. I have this HTML: {% load i18n %} <select id="{{ select_id }}" name="{{ select_name }}" class="form-control"> <option value="">{% trans 'Alege TVA' %}</option> {% for vat_rate in vat_rates %} {{ vat_rate.text_tooltip }} <option value="{{ vat_rate.actual_value }}" title="{{ vat_rate.text_tooltip }}"> {{ vat_rate.full_name }} </option> {% endfor %} </select> and this in JavaScript: $('#id_vat_value').select2({ placeholder: gettext("Alege TVA"), escapeMarkup: function (m) { return m; }, matcher: function (params, data) { return TrimSpacesSelect2(params, data); }, }) is there any way to add the tooltip to the select2 li items? I tried to add it in select2:open, but i don't think is really good, right now it is showing the tooltip but i don't know if it's the best choice. .on('select2:open', function () { setTimeout(function () { $('.select2-results__option').each(function () { var $option = $(this); var optionId = $option.attr('id'); var originalOption = $('#id_vat_value option').filter(function () { return $(this).val() === optionId.split('-').pop(); }); var tooltip = originalOption.attr('data-original-title'); if (tooltip) { $option.attr('title', tooltip); $option.attr('data-toggle', 'tooltip'); } }); $('[data-toggle="tooltip"]').tooltip({ delay: {show: 500, hide: 0}, trigger: "hover" }); }, 100); }); -
Where to deploy Next.js & Django
I have created a project that uses Next.js on the frontend and Django on the backend, the web app uses JWT for requests. Now I want to deploy the project and want to ask where I should do it? Do I have to use two different services or can I use one service for both? I have done the Next.js getting started tutorial where you get to create a dashboard app and deploy it using Vercel, that was very simple, can I do the same with this project? Also, I'd like to add that the database used currently while I'm developing is the default SQLite but I do want to switch to a "real" database like PostgreSQL, for example, later when launching. -
Django Celery: Kombu connection refused error
It seems a bit odd, maybe I'm missing something, but whenever I send tasks to celery queue it suddenly gives error: AttributeError: 'ChannelPromise' object has no attribute 'value' It works at first but if tasks are sent to the queue at a slightly higher frequency, it suddenly starts to give the above error. Looks like some kind of blocked process or something like that. Broker is aws sqs Celery settings: CELERY_RESULT_BACKEND = 'django-db' CELERY_BROKER_URL = 'sqs://' CELERY_BROKER_TRANSPORT_OPTIONS = { 'region' : 'us-south-1', #temp name 'visibility-timeout' : 3600, 'polling-interval' : 10 } CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Kolkata' Packages: celery = ">=5.0.5" django = "==4.2.16" kombu = "==5.4.2" django-celery-beat = ">=2.0.0" django-celery-results = ">=2.2.0" Files: project/init.py from .celery import app as celery_app __all__ = ['celery_app'] project/celery.py import os from celery import Celery from project.settings import settings # set the default Django settings module for the 'celery' program. #settings are kept inside a separate folder for multiple envs [project/settings/settings_prod.py,project/settings/settings_stag.py,project/settings/settings.py] os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings.settings') app = Celery('project') app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): pass Complete error trace: kombu.exceptions.OperationalError: [Errno 111] Connection refused on next try in production. complete … -
How to secure JWT tokens with a DRF backend supporting both mobile and SPA clients?
I am developing an application that uses the Django REST Framework to provide a REST API. I intend to protect it using token authentication, with the help of simple_jwt. Example API overview: /auth/login/: Supports POST, requires valid username and password, returns a JWT access and refresh /auth/refresh/: Supports POST, requires a valid refresh token, returns new access and refresh tokens /protected/endpoint/: Requires a valid access token From reading on CSRF I have gathered: CSRF is only needed if cookies are involved, so only use for the SPA client To persist the JWT token: SPA: Persist in an httpOnly cookie with secure=true and same-origin set App: Persist in however the app persistent state works So far so good, however, this would mean that my REST API needs to both require CSRF tokens for requests coming from the SPA and not require/ignore CSRF tokens for requests coming from mobile app clients. Since this is logically impossible I was first thinking of implementing 2 separate APIs. I.e.: /spa/auth/..., /spa/protected/...: For SPA clients, where all endpoints require a CSRF token /mobile/auth/..., /mobile/protected/...: For mobile clients, where all endpoints are CSRF exempt. But doing this just means that my CSRF protection is useless, since a … -
How to fetch real-time google cloud run job logs?
I am building a CI/CD kind of tool which is actually a web app. The stack is django-rest-framework on the backend and React (Vite) on the frontend. Currently the pipeline running and the actions from the stages that are running are all working, the jobs are being created, ran, deleted and it all works fine. This is all happening through the Google Cloud Run Jobs. For the app to make sense, I need to be able to get real-time logs from that specific job while it is running. Currently I have a crude temporary implementation where I am using the Google Cloud Logging API with filters to periodically get the logs for that job. This is the mentioned crude implementation: from google.cloud import logging_v2 from apps.docker_app.utils.google_credentials import get_google_credentials def _stream_job_logs(logging_client, log_filter): seen_entries = set() while True: entries = logging_client.list_entries(filter_=log_filter) for entry in entries: if entry.insert_id not in seen_entries: seen_entries.add(entry.insert_id) yield entry time.sleep(1) class GoogleLogsClient: def __init__(self): storage_credentials = get_google_credentials() self.client = logging_v2.Client(credentials=storage_credentials) def stream_job_logs(self, log_filter): for entry in _stream_job_logs( logging_client=self.client, log_filter=log_filter ): if "All stages completed successfully" in entry.payload: break timestamp = entry.timestamp.isoformat() print("* {}: {}".format(timestamp, entry.payload)) While this does work, I am limited to 60 read requests to the … -
Django Admin Not Displaying `creation_date` Field Despite Being in `list_display`
I have a Django project where I'm working on an e-commerce application. I'm using SQLite as my database, and I'm trying to add a creation_date field to my VendorProduct model so that it records when a product was created. What I Did I added the creation_date field to my VendorProduct model like this: models.py (VendorProduct Model) from django.db import models from django.utils.timezone import now from userauths.models import CustomUser class VendorProduct(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True, blank=True) creation_date = models.DateTimeField(auto_now_add=True, blank=True, null=True) def __str__(self): return self.title Migrations I ran the following commands to apply the migration: python manage.py makemigrations vendorpannel python manage.py migrate vendorpannel Then, I verified that the creation_date column exists in my database using: from django.db import connection with connection.cursor() as cursor: cursor.execute("PRAGMA table_info(vendorpannel_vendorproduct);") columns = cursor.fetchall() for column in columns: print(column) The output confirms that creation_date exists in my database: (7, 'creation_date', 'datetime', 0, None, 0) Admin Panel Configuration I updated my admin panel to display creation_date: admin.py from django.contrib import admin from .models import VendorProduct class VendorProductAdmin(admin.ModelAdmin): list_display = ('creation_date') readonly_fields = ('creation_date',) admin.site.register(VendorProduct, VendorProductAdmin) Problem: creation_date Not Showing in Django Admin Even after making these changes and applying migrations, the creation_date field is not appearing in … -
Cloudinary Upload Issue on PythonAnywhere: MaxRetryError
I'm developing a Django application that uses Cloudinary for image storage. When running the project locally, everything works fine, and images upload successfully. However, when I deploy the project on PythonAnywhere, I get the following error when trying to upload an image from the admin panel: Unexpected error - MaxRetryError("TCPKeepAliveHTTPSConnectionPool(host='api.cloudinary.com', port=443): Max retries exceeded with url: /v1_1/di6geozk1/image/upload (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x748d7df0b520>: Failed to establish a new connection: [Errno 111] Connection refused'))") Configuration in settings.py: CLOUDINARY_STORAGE = { 'CLOUD_NAME': env('CLOUDINARY_STORAGE_CLOUD_NAME', default=''), 'API_KEY': env('CLOUDINARY_STORAGE_API_KEY', default=''), 'API_SECRET': env('CLOUDINARY_STORAGE_API_SECRET', default=''), 'SECURE': True, 'API_PROXY': 'http://proxy.server:3128' } ### Things I've already checked: - The credentials (CLOUD_NAME, API_KEY, API_SECRET) are correctly set. - In my local environment, images upload successfully to Cloudinary. - In PythonAnywhere, the connection is refused. - I tried removing the 'API_PROXY' setting, but the error persists. -
wagtail empty results in pages api
I am getting empty results in wagtail api pages list. my models.py from django.db import models from wagtail.models import Page from wagtail.admin.panels import FieldPanel from wagtail.api import APIField from wagtail.fields import StreamField from wagtail.admin.panels import FieldPanel from streams import blocks class FlexPage(Page): banner_title = models.CharField(blank=True, max_length=200) banner_text = models.CharField(blank=True, max_length=2000) banner_cta_text = models.CharField(blank=True, max_length=100) banner_cta_url = models.URLField(blank=True, default="") banner_image = models.ForeignKey( "wagtailimages.Image", null=True, blank=True, on_delete=models.SET_NULL, related_name="+", ) content = StreamField( [ ("youtube_block", blocks.YouTubeBlock()), ("image_block", blocks.ImgBlock()), ("section_heading", blocks.SectionHeading()), ("title_text_two_columns", blocks.TitleTextTwoColumns()), ], null=True, blank=True, use_json_field=True, ) content_panels = Page.content_panels + [ FieldPanel("banner_title", classname="full"), FieldPanel("banner_text"), FieldPanel("banner_cta_text"), FieldPanel("banner_cta_url"), FieldPanel("banner_image"), FieldPanel("content"), ] api_fields = [ APIField("banner_title"), APIField("banner_text"), APIField("banner_cta_text"), APIField("banner_cta_url"), APIField("banner_image"), APIField("content"), ] blocks.py from wagtail import blocks from wagtail.blocks.field_block import (BooleanBlock, CharBlock, PageChooserBlock, TextBlock, URLBlock) from wagtail.images.blocks import ImageChooserBlock as DefaultImageChooserBlock class ImageChooserBlock(DefaultImageChooserBlock): def get_api_representation(self, value, context=None): if value: return { "id": value.id, "title": value.title, "original": value.get_rendition("original").attrs_dict, "thumbnail": value.get_rendition("fill-120x120").attrs_dict, } class YouTubeBlock(blocks.StructBlock): url = URLBlock(required=True) class Meta: template = "streams/youtube.html" label = "Youtube" class ImgBlock(blocks.StructBlock): image = ImageChooserBlock() cta = URLBlock(required=False) class Meta: template = "streams/image_block.html" label = "Image" class SectionHeading(blocks.StructBlock): title = blocks.CharBlock(required=True, help_text="add your title") class Meta: template = "streams/section_heading.html" label = "section heading" class TitleTextTwoColumns(blocks.StructBlock): title = blocks.CharBlock(required=False) content = blocks.CharBlock(required=False) left_title … -
Unable to display data from QuerySet in Django templates
I'm trying to implement a simple search for data on a website. If we specify the a tag in the "search_results.html" template, then all the information that is in it is not displayed, but if we remove the a tag, then everything works, why can this happen? That is, this information is not displayed for me - <a href="{{ article.get_absolute_url }}">{{ article.title }}</a> file urls.py urlpatterns = [ path("search_page/", views.SearchPageView.as_view(), name="searchpageurl") ] file views.py class SearchPageView(TemplateView): template_name = "search/search_results.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) query = self.request.GET.get("q", "") context["query"] = query if query: articles = ListArticles.objects.filter( Q(title__icontains=query) | Q(text__icontains=query), is_publish=True ) context["results"] = {"articles": articles} else: context["results"] = {} return context file model class ListArticles(models.Model): title = models.CharField(max_length=100, verbose_name="Заголовок") text = models.TextField(verbose_name="Текст") images = models.ImageField(upload_to="articles/", verbose_name="Изображение") date_publsh = models.DateTimeField(verbose_name="Дата Публикации") date_modified = models.DateTimeField(auto_now=True) is_publish = models.BooleanField(verbose_name="Опубликованно/Неопубликованно") cats = models.ForeignKey( Category, on_delete=models.CASCADE, verbose_name="Категория" ) slug = models.SlugField(max_length=100, verbose_name="Слаг") tag = models.ManyToManyField(Tag, related_name="articles", verbose_name="Теги") def __str__(self): return self.title def get_absolute_url(self): return reverse("singlearticles", kwargs={"detail_slug": self.slug}) file search_results.html {% extends 'base.html' %} {% block content %} <h1>Результаты поиска для "{{ query }}"</h1> {% if results.articles %} <h2>Статьи:</h2> <ul> {% for article in results.articles %} <li><a href="{{ article.get_absolute_url }}">{{ article.title }}</a></li> {% empty %} … -
How do i publish a django on localserver publibly
I want to publish a django project on an old laptop that's been lying around for a long time. I've just installed the linux server setup. Any help is appreciated. And it's connected to a postgres database. -
Why does AWS ALB Health Checks Fail with Correct Security Group (EC2, Docker, nginx-proxy, ACM)?
I'm having trouble getting my AWS Application Load Balancer (ALB) health checks to pass when my EC2 instance's security group is configured correctly. The site works when I open port 443 to the world (0.0.0.0/0), but fails when I restrict it to the ALB's security group, even with Source/Destination Check disabled. EC2 Instance Configuration: Docker Compose runs nginx-proxy, acme-companion, Django (web), and other services. nginx-proxy is mapped to ports 80 and 443 on the host. VIRTUAL_HOST is set to my domain. VIRTUAL_PORT is correctly set to 8000 EC2 Instance Security Group: Correct Configuration (Failing): Allows inbound HTTPS (port 443) only from the ALB's security group (e.g., sg-xxxxxxxx). Temporary Workaround (Working): Allows inbound HTTPS (port 443) from 0.0.0.0/0. Source/Destination Check is disabled on the EC2 instance. Request Flow: Client Request -> Route 53 -> Application Load Balancer (HTTPS:443) -> AWS WAF -> ALB Target Group (HTTPS:443) -> EC2 Instance (port 443, nginx-proxy) -> Docker Container (port 8000, Django) ALB Configuration: Listener on port 80 (HTTP) redirects to HTTPS (443). Listener on port 443 (HTTPS) forwards to the target group. ALB Security Group: Allows inbound on ports 80 and 443 from 0.0.0.0/0. Target Group health checks: Protocol: HTTPS Port: 443 Path: /api/v1/health/ … -
drf use social auth with simple-jwt library AttributeError: Manager isn't available
I try to customize drf_social_oauth2 with drf simple-jwt I use core.models instead of standard social_oauth2 models, but got 500 status code, error "AttributeError: Manager isn't available; 'oauth2_provider.Application' has been swapped for 'core.Application'" My files: settings.py INSTALLED_APPS = [ ... 'oauth2_provider', 'social_django', 'drf_social_oauth2', 'apps.core', ... ] ... 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', 'drf_social_oauth2.authentication.SocialAuthentication', ), ... AUTHENTICATION_BACKENDS = { 'django.contrib.auth.backends.ModelBackend', 'drf_social_oauth2.backends.DjangoOAuth2', 'social_core.backends.google.GoogleOAuth2', 'social_core.backends.apple.AppleIdAuth', } CTIVATE_JWT = True DRFSO2_URL_NAMESPACE = "drf" OAUTH2_PROVIDER = { "ACCESS_TOKEN_EXPIRE_SECONDS": 30 * 60, "REFRESH_TOKEN_EXPIRE_SECONDS": 24 * 60 * 60, "ACCESS_TOKEN_GENERATOR": "apps.core.oauth2_tokens_generators.generate_access_token", "REFRESH_TOKEN_GENERATOR": "apps.core.oauth2_tokens_generators.generate_refresh_token", } OAUTH2_PROVIDER_APPLICATION_MODEL = "core.Application" OAUTH2_PROVIDER_ACCESS_TOKEN_MODEL = "core.AccessToken" OAUTH2_PROVIDER_REFRESH_TOKEN_MODEL = "core.RefreshToken" OAUTH2_PROVIDER_ID_TOKEN_MODEL = "core.IDToken" OAUTH2_PROVIDER_GRANT_MODEL = "core.Grant" # GOOGLE OAUTH2 SETTINGS SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = config("SOCIAL_AUTH_GOOGLE_OAUTH2_KEY", default="") SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = config("SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET", default="") SOCIAL_AUTH_APPLE_ID_CLIENT = config("SOCIAL_AUTH_APPLE_ID_CLIENT", default="") SOCIAL_AUTH_APPLE_ID_TEAM = config("SOCIAL_AUTH_APPLE_ID_TEAM", default="") SOCIAL_AUTH_APPLE_ID_KEY = config("SOCIAL_AUTH_APPLE_ID_KEY", default="") SOCIAL_AUTH_APPLE_ID_SECRET = config("SOCIAL_AUTH_APPLE_ID_SECRET", default="") core.models """ Module for defining OAuth2 models for token management. """ from django.db.models import CharField from oauth2_provider import models class Application(models.AbstractApplication): """ Customized OAuth2 Application model. Inherits from `oauth2_provider.models.AbstractApplication`. """ class Grant(models.AbstractGrant): """ Customized OAuth2 Grant model. Inherits from `oauth2_provider.models.AbstractGrant`. """ class AccessToken(models.AbstractAccessToken): """ Customized OAuth2 Access Token model. Inherits from `oauth2_provider.models.AbstractAccessToken`. Attributes: token (str): The access token value. """ token = CharField( max_length=2048, unique=True, db_index=True, ) class RefreshToken(models.AbstractRefreshToken): """ Customized OAuth2 … -
Django Formset Nested Structure Not Posting Correctly for Dynamic Fields
I’m working on a Django nested formset where users can: Add multiple colors to a product. For each color, add multiple sizes dynamically using JavaScript. Each size should have its own size_name, stock, and price_increment field. Issue When submitting the form, Django is incorrectly grouping multiple size field values into lists instead of treating them as separate entries. Expected Django POST Data (Correct Structure) sizes-0-0-size_name = "Small" sizes-0-0-stock = "100" sizes-0-0-price_increment = "50" sizes-0-1-size_name = "Medium" sizes-0-1-stock = "150" sizes-0-1-price_increment = "75" Actual Django POST Data (Incorrect Structure) sizes-0-0-size_name = ["Small", "Medium"] sizes-0-0-stock = ["100", "150"] sizes-0-0-price_increment = ["50", "75"] Instead of separate fields for each size, Django is grouping values into a single list. The sizes-0-TOTAL_FORMS field is appearing twice in the POST request, which might indicate a JavaScript duplication issue. Debugging the Request Data (request.POST) <QueryDict: { 'colors-TOTAL_FORMS': ['1'], 'sizes-0-TOTAL_FORMS': ['1', '1'], # This should be a single value, not duplicated 'sizes-0-0-size_name': ['Small', 'Medium'], 'sizes-0-0-stock': ['100', '150'], 'sizes-0-0-price_increment': ['50', '75'] }> Potential Causes: JavaScript Issue: Dynamic form addition might be incorrectly naming inputs, causing Django to interpret multiple values as a list. TOTAL_FORMS for sizes might not be updated properly, leading to duplicate values. Django Formset Issue: Django … -
How to implementing pagination for Django 5 admin sidebar filters?
The Problem Django's admin sidebar filters show all options without pagination, which becomes unwieldy when you have hundreds of related objects: By Study • All • Study-001: Genetic markers in mice • Study-002: Effects of caffeine ... • Study-999: Soil microbiome analysis With many options, this makes the UI unusable and harms performance. Our Approach We implemented custom filters with pagination to display only a subset of options at a time: By Study • All • Study-001: Genetic markers in mice • Study-002: Effects of caffeine ... • Study-010: Plant growth factors Page 1 of 100 | Next > Implementation Custom filter class: class StudyListFilter(SimpleListFilter): title = _('By Study') parameter_name = 'study__id__exact' template = 'admin/filter_pagination.html' # Custom template def lookups(self, request, model_admin): # Return minimal data - real items are provided in the template return [('', 'All')] def queryset(self, request, queryset): if self.value(): return queryset.filter(study__id=self.value()) return queryset Modified admin class: @admin.register(Assay) class AssayAdmin(admin.ModelAdmin): list_filter = (StudyListFilter, 'measurement_type') change_list_template = 'admin/study_change_list.html' def changelist_view(self, request, extra_context=None): extra_context = extra_context or {} # Get paginated studies studies = Study.objects.all().order_by('id') paginator = Paginator(studies, 10) page_number = request.GET.get('filter_page', 1) page_obj = paginator.get_page(page_number) # Pass pagination data to template extra_context.update({ 'filter_page_obj': page_obj, 'filter_items': [(s.id, f"{s.accession_code} - … -
CSS File not loading in Django
I have the style.css in the root static folder. When I browse the page or the css file directly in browser, it shows a 404 error. This the folder structure: reviews > templates > reviews > base.html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="{% static "style.css" %}" /> </head> </html> Feedback > Feedback > settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static", ] Error: GET http://127.0.0.1:8000/static/style.css net::ERR_ABORTED 404 (Not Found) -
HTMLCollection does not function for loops
I encountered a problem of making a for loop after a document.getElementsByClassName("..") document.addEventListener('DOMContentLoaded', function() { let btnTitle = document.getElementsByClassName("button-title"); console.log("Number of button-title elements found:", btnTitle.length); if (btnTitle) { console.log("all button: ", btnTitle); Array.from(btnTitle).forEach((btn) => { console.log("btn", btn); btn.addEventListener("click", (event) => { const courseContent = btn.nextElementSibling; console.log("courseContent:", courseContent) courseContent.classList.toggle('show'); }) }) } } It will be returning like the image Image of console I don't understand why btnTitle.length return 0, but it still has btnTitle in console, and it has one element who owns a length: 1. I did it because I want to debug why the button's function is not working And this is how I create the buttons by javascript (if it's necessary to debug): const courseAndTest = document.getElementById("course_and_test"); if(courseAndTest) { //Fetch data const student_id = courseAndTest.dataset.studentId; fetch(`/student_tests/${student_id}`) .then(response => response.json()) .then(data => { if (!data || !data.courses) { courseAndTest.innerHTML = "<p>No courses found.</p>"; return; } //Make div for each course data.courses.forEach(course => { let course_nb = 0 const course_container = document.createElement("div"); course_container.innerHTML += `<button class="btn btn-primary button-title"><h3>Course ${course_nb += 1}: ${course.course.title}</h3></button>` const course_container_2 = document.createElement("div"); course_container_2.classList.add("toggle-course"); //Add all lectures of course course.lectures.forEach(lecture => { const lecture_container = document.createElement("div"); lecture_container.style.overflowX = "auto"; lecture_container.innerHTML += `<h4>${lecture.title}</h4>` //create a table with … -
How to disable Django Debug Toolbar while rendering a template?
I'm using Django Debug Toolbar in my development environment, and it's been very helpful for debugging. However, I want to disable it when rendering a specific template. Is there a way to conditionally disable the debug toolbar for certain views or templates? Here’s what I’ve tried so far: Using settings.DEBUG: I know that the toolbar is only shown when DEBUG = True in settings.py, but I don't want to disable it for the entire project, just for specific views or templates. Template Context: I also considered passing a context variable to the template to control the toolbar's visibility, but I’m not sure how to integrate this with the toolbar's behavior. Here’s a simplified version of my view: from django.shortcuts import render def my_view(request): context = {'some_data': 'data'} return render(request, 'my_template.html', context) And in my settings.py: DEBUG = True if DEBUG: INSTALLED_APPS += ['debug_toolbar'] MIDDLEWARE += ['debug_toolbar.middleware.DebugToolbarMiddleware'] django_debug_toolbar version is 3.8.1 Is there a way to disable the Django Debug Toolbar specifically for this view or template? -
Django Formset Dynamic Add/Remove Not Working for Colors, Sizes, and Images
Problem Statement I am working on a Django formset where users can dynamically add/remove colors, sizes, and images when adding a product. The structure of my formset is as follows: A product can have multiple colors. Each color can have multiple sizes. Each color can have multiple images. Users should be able to dynamically add/remove colors, sizes, and images using JavaScript. Expected Behavior Clicking "Add Color" should create a new color form with its own size and image sections. Clicking "Add Size" within a color should add a new size only to that specific color. Clicking "Add Image" within a color should add a new image only to that specific color. Clicking "Remove Color" should remove the specific color section. Current Issue Only the "Remove Color" button works. "Add Color", "Add Size", and "Add Image" buttons are not working. No new elements are being appended to the DOM when clicking the buttons. Debugging Attempts ✔ Checked Django Formset Management Forms (they exist). ✔ Verified event listeners are attached using console.log(). ✔ Ensured cloneNode(true) properly copies elements. ✔ Checked for JavaScript errors in the console (no syntax errors). Django Forms & Formsets Forms (forms.py) from django import forms from django.forms import …