Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Is it correct to modify `django.db.connections.databases` dynamically to multiple databases? Or is it better to deploy a separate API per client?
This is my first time developing a multi-tenant SaaS application in Django, in this SaaS each company has its own PostgreSQL database, and these databases are created dynamically when a company registers. I cannot predefine all databases in settings.DATABASES, as companies can register at any time without requiring a server restart. My current solution uses Middleware to detect the company from the subdomain or a JWT token and then modify connections.databases at runtime to configure the connection to the company's database: import redis from django.db import connections from django.core.exceptions import ImproperlyConfigured from django.utils.connection import ConnectionDoesNotExist from rest_framework_simplejwt.authentication import JWTAuthentication from myapp.models import Company # Company model stored in the global database class CompanyDBMiddleware: def __init__(self, get_response): self.get_response = get_response self.jwt_authenticator = JWTAuthentication() self.cache = redis.Redis(host='localhost', port=6379, db=0) def __call__(self, request): company_db = self.get_database_for_company(request) if not company_db: raise ImproperlyConfigured("Could not determine the company's database.") # Register connection only if it does not exist in `connections.databases` if company_db not in connections.databases: connections.databases[company_db] = { 'ENGINE': 'django.db.backends.postgresql', 'NAME': company_db, 'USER': 'postgres', 'PASSWORD': 'your_password', 'HOST': 'localhost', 'PORT': '5432', 'CONN_MAX_AGE': 60, # To avoid opening and closing connections on each request } request.company_db = company_db response = self.get_response(request) # Close connection after the response try: … -
handle auth workflow with django API and react
I have a frontend app written in react I have a backend application which is a django server. On top of that I am working with a 3rd party True Layer (Open Banking API) The first thing I want to implement is the authentication which I did correctly. However, I am trying to write a method to refresh my access_token thanks to the refresh_token given by the TrueLayer API when user first authenticate. The problem is that from what I read online the good practice is to have the refresh_token stored into the HTTP only cookies. So I did something like this def truelayer_callback(request): code = request.GET.get('code') token_data = { "grant_type": "authorization_code", "client_id": settings.TRUELAYER_CLIENT_ID, "client_secret": settings.TRUELAYER_CLIENT_SECRET, "redirect_uri": REDIRECT_URI, "code": code, } try: data = requests.post(TOKEN_URL, data=token_data).json() access_token = data.get('access_token') refresh_token = data.get('refresh_token') if access_token: query_params = urlencode({'token' : access_token}) response = HttpResponseRedirect(f'{FRONTEND_URL}?{query_params}') response.set_cookie(key='refresh_token', value=refresh_token, httponly=True, secure=False, samesite='Lax') return response return HttpResponseRedirect(f'{FRONTEND_URL}?error=No access token received') except Exception as e: return HttpResponseRedirect(f'{FRONTEND_URL}?error={str(e)}') I set the cookie refresh_token in the response. But in my next method, which is the method called to refresh the access_token when I try to access my refresh_token from cookies I get None: def check_refresh_cookie(request): refresh_token = request.COOKIES.get("refresh_token") # … -
Does Django automatically recognize registration/login.html as the login template?
Does Django automatically recognize registration/login.html as the login template? I'm working on a Django project and want to use Django's built-in authentication system for user login. If I don't set in url in urls.py My question is: Does Django automatically recognize registration/login.html as the default login template? If so, how does Django determine this file's location? Do I need to set anything in settings.py to make this work? Where is written the logic for this built in login -
Django WSGI and ASGI
This is my project structure. . ├── chat # <== my app name │ ├── apps.py │ ├── consumers.py │ ├── __init__.py │ ├── migrations │ │ ├── __init__.py │ ├── models.py │ ├── routing.py │ ├── templates │ │ └── chat │ │ ├── index.html │ │ └── room.html │ ├── urls.py │ └── views.py ├── config # <== project configuration │ ├── asgi.py │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── manage.py setting.py file ALLOWED_HOSTS = ["*"] INSTALLED_APPS = [ "daphne", ..., ..., "chat", ] # for HTTP protocal WSGI_APPLICATION = "config.wsgi.application" # for Websocket protocal ASGI_APPLICATION = "config.asgi.application" chat/urls.py file from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), ] wsgi.py file from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings") application = get_wsgi_application() chat/routing.py file from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r"ws/chat/(?P<room_name>\w+)/$", consumers.ChatConsumer.as_asgi()), ] asgi.py file from chat.routing import websocket_urlpatterns os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings") application = ProtocolTypeRouter( { "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack(URLRouter(websocket_urlpatterns)), ), } ) After setting up all the configurations, I ran the HTTP and WebSocket servers on separate ports: Run the HTTP server (with Gunicorn): gunicorn config.wsgi:application --bind 0.0.0.0:8000 Run the WebSocket server (with Daphne): … -
Split data of an Ajax call to multiple div in Django
I have this ajax call $.ajaxSetup({ data: {txtSearch: $('#txtSearch').val(), prefilter: $('#prefilter').val(),csrfmiddlewaretoken: '{{ csrf_token }}' },}); $.ajax({ type: "POST", url: "article-filter2/", success: function (data) { $("#div_tab_search_results_contact").html(data.html_table); // working $("#div_tab_search_results_company").html(data.html_table); // not working if I call it a second time } }); data.html_table contains 2 tables and I would like to put the first one in $("#div_tab_search_results_contact") and the second one in $("#div_tab_search_results_company") based on the id's of the tables. I tried to search but what I found was in PhP Not able to split the Ajax response in separate Div Here is the end of my view.py article-filter2/ : def article_filter2(request): data = dict() [...] data['html_table'] = render_to_string('grid.html', {'available_lessons': available_lessons, 'available_lessons_company': available_lessons_company },request=request) return JsonResponse(data) Thanks to anybody that can help me