Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Embedding a Web Application Using an Iframe
I have a Django application (A), and one of my clients wants to embed it within their application (B) using an iframe. The client application can be built with any framework, and we have no control over its code. Additionally, both applications are hosted on entirely different domains. To enable this setup, we need to fine-tune the settings in our Django application A to allow embedding within client application B. Below is a test HTML code snippet used to embed the web application, which I have hosted using a free hosting service. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>URL Loader</title> <style> body { font-family: Arial, sans-serif; text-align: center; margin: 20px; } iframe { width: 100%; height: 80vh; border: 1px solid #ccc; } </style> </head> <body> <h2>Loaded URL in iFrame</h2> <iframe id="urlFrame" src="https:/xyz.com" ></iframe> </body> </html> Django Configuration: Python 3.6 Django: 2.2.5 Changes made: Updated Django settings to permit the domain to load the application. Some of the settings below should be hardened for security in production, as they are intended only for POC purposes.: DEBUG = True Removed X_FRAME_OPTIONS = "DENY" and used CSP_FRAME_ANCESTORS = ("'self'", "*") CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True CSRF_TRUSTED_ORIGINS = … -
How To Append & Send File data in a multipart react form with Django backend with Nested JSON
So, I have a form data with the corresponding JSON format project_status: 'OPEN', project_title: '', project_code: '', start_date: '', end_date: '', duration: '', engagement_year: '', financial_year: '', project_budget: '', domain: '', project_type: '', project_mou: null, other_docs: null, thirdAgencyDetails: { government_body: '', scheme_name: '', sanctioned_budget: '', industry_contribution: '', government_contribution: '', agreement: null, sanction_letter: null, proposal_doc: null }, facultyDetails: [], I trying to send this data to Django backend which has the following model class Project(models.Model): user = models.CharField(max_length=15, null=True) project_title = models.CharField(max_length=250, null=True) project_code = models.CharField(max_length=250, null=True) start_date = models.DateField(max_length=10, null=True, default='') end_date = models.DateField(max_length=10, null=True, default='') duration = models.CharField(max_length=255) engagement_year = models.IntegerField() financial_year = models.CharField(max_length=255) project_budget = models.DecimalField(max_digits=10, decimal_places=2) domain = models.CharField(max_length=250, null=True) project_type = models.CharField(max_length=255) project_status=models.CharField(max_length=250, blank=True) thirdAgencyDetails = models.OneToOneField(ThirdAgencyDetail, on_delete=models.CASCADE, null=True, blank=True) project_mou = models.FileField(upload_to='R&D_docs/', blank=True) other_docs = models.FileField(upload_to='R&D_docs/', blank=True) with a one to one field to class ThirdAgencyDetail(models.Model): government_body = models.CharField(max_length=255) scheme_name = models.CharField(max_length=255) sanctioned_budget = models.DecimalField(max_digits=10, decimal_places=2) industry_contribution = models.DecimalField(max_digits=10, decimal_places=2) government_contribution = models.DecimalField(max_digits=10, decimal_places=2) agreement = models.FileField(upload_to='jointProject_thirdAgency_docs/',blank=True) sanction_letter = models.FileField(upload_to='jointProject_thirdAgency_docs/',blank=True) proposal_doc = models.FileField(upload_to='jointProject_thirdAgency_docs/',blank=True) I have written a form uploading code refer code gist here I am unable to append the files for 'thirdAgencyDetails' since it is a nested JSON in similar manner to if (formData.project_mou) … -
Prevent Multiple Users from Booking the Same Table at the Same Time in Django
I have a Booking model where users can book a restaurant table for a specific date and time. However, I want to ensure that multiple users cannot book the same table at the same time. Here’s my model: class Booking(TimeStampWithCreatorModel, TerminalMixin, SoftDeletableModel): table = models.ManyToManyField(RestaurantTable, related_name="booking_table") customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name="booking_customer") no_of_people = models.IntegerField() booking_date = models.DateField() booking_time = models.TimeField(null=True, blank=True) note = models.TextField(blank=True) accept_terms_and_conditions = models.BooleanField(default=False) receive_emails = models.BooleanField(default=False) class Meta: ordering = ("-created",) What I've Tried I attempted to use select_for_update to lock the rows while making a booking, but when multiple users try to book the same table at the exact same time, duplicate bookings are still created in some instances. Here’s the approach I used: from django.db import transaction def create_booking(customer, table_ids, booking_date, booking_time, no_of_people): with transaction.atomic(): tables = RestaurantTable.objects.filter(id__in=table_ids).select_for_update() if Booking.objects.filter(table__in=tables, booking_date=booking_date, booking_time=booking_time).exists(): raise ValueError("Table already booked for this time slot.") booking = Booking.objects.create( customer=customer, no_of_people=no_of_people, booking_date=booking_date, booking_time=booking_time ) booking.table.set(tables) return booking The Problem Despite using select_for_update, when multiple instances try to book at the same time, the check Booking.objects.filter(...) does not prevent race conditions properly. I assume this happens because Django’s ManyToManyField does not lock relationships the same way ForeignKey does. Expected Outcome Prevent … -
Create a Mock Request for django rest framework
I am trying to createa mock Request for a post method in django rest framework and tried: factory = APIRequestFactory() data = {"hello": 1} print(data) django_request = factory.post(url, data, format="json") print("body:", django_request.body) print("ct:", django_request.content_type) r = Request(django_request) print(r.data) The printing correctly shows the body to be set to a (binary) string. However the final r.data is an empty list. How do I set the data? -
Django css not rendering in Production
In my Django5 app everything works fine in development under venv but once I load the application into a Docker container with Debug=False I don't seem to get my CSS rendered properly. Whats really wierd is the CSS loading appears to be correct, I just don't get my custom css hero image and colors, and the admin css is also broken. I'm using gunicorn with nginx serving static data. I do see my favicon.ico which is served from the same /static/ folder and the css, js, etc. folders all exist in the nginx container as expected. I view source and click on the links and they're all there. In Django settings.py I have: from pathlib import Path import os import environ env = environ.Env( DEBUG=(bool, False) ) BASE_DIR = Path(__file__).resolve().parent.parent environ.Env.read_env(os.path.join(BASE_DIR, '.env')) SECRET_KEY = env('SECRET_KEY') DEBUG = env('DEBUG') ALLOWED_HOSTS = ['*'] . . . STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') Changing STATIC_ROOT to the actual container path '/usr/share/nginx/html/static/' didn't change the behaviour. In my root urls.py: urlpatterns = [ path("admin/", admin.site.urls), . . . ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) My dockerfile-compose.yaml includes collectstatic: web: build: context: . dockerfile: Dockerfile command: > sh -c "python manage.py collectstatic --noinput && python manage.py … -
How to disable the options in select with Django
I created a calendar with dates where appointments can be made. I then created a form to select appointments. I want each time an appointment is made, it to be grayed out for the exact day and time it was made. For March 2, 2025 I booked an appointment at 9am, for January 24, I booked an appointment at 8am and for March 6, 2025, I booked an appointment at 2:15pm. However, as you can see in the picture, when I click on March 2, 2025, the times 8am, 9am and 2:15pm are all grayed out even though I used them for different days. Thanks in advance #********************************** def formatday(self, day, rdvs): select_hour = RdvForm() select_dat = Rdv.objects.all().values() p = len(select_dat)`enter code here` rr =len(select_hour['start_time']) ls_h = [] ls_d =[] ls_dd=[] # add value in list for i in range(p): ls_h.append(select_dat[i]["start_time"]) for lis_d in range(p): f = str(select_dat[lis_d]["select_date"]) ls_d.append(f[:7]) #list day year for dd in range(p): ff = str(select_dat[dd]["select_date"]) ls_dd.append(int(ff[8:])) year_month_curent =str (self.year)+'-'+str("{:02}".format(self.month)) htm = f'<select name="start_time" id="id_start_time">' for i in range(rr): if select_hour['start_time'][i].data['value'] in ls_h and year_month_curent in ls_d and day in ls_dd: htm+= f'<option class="{i}" disabled="disabled" value="{select_hour['start_time'][i].data["value"]}">{select_hour['start_time'][i].data["value"]}</option>' else: htm+= f'<option value="{select_hour['start_time'][i].data["value"]}">{select_hour['start_time'][i].data["value"]}</option>' htm+=f'</select>' #***************** for i in range(rr): if … -
Exception when trying to launch django project debug in VS code
Hi I have a django project (4.2.2) and when I start the project from the terminal inside VS Code using "python3 manage.py runserver" everything works perfectly. But I want to debug it so I created a launch.json file to start it as debug Here is what it contains: { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python Debugger django", "type": "debugpy", "request": "launch", "program": "${workspaceFolder}/manage.py", "console": "integratedTerminal", "django": true, "args": [ "runserver", ] } ] } When I try to start the project using debug button I get the following error: django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 or psycopg module I have installed psycopg library as if I look at my requiremnts.txt I have psycopg==3.2.4 psycopg-binary==3.2.4 Not sure what is the problem? In debug mode the error is display in my models.py file: from django.db import models class User(models.Model): # <-- here is the error """ User entity """ id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=80) last_name = models.CharField(max_length=100) # created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.first_name} {self.last_name}" -
Manually access content from Form fields in Django
I'm in a position where I would like to submit content to a form that is not defined in a Forms class. For example, in my forms.py: class AnalyseForm(forms.Form): TYPES = (('a', 'Type A'),('b', 'Type B'), ('c', 'Type C')) filename = forms.FileField(label="Document to Aalyse") doctype = forms.ChoiceField(choices=TYPES, label="Doc Type:") and in my views.py: I am trying to send an additional variable that doesn't exist in the Form class, because I defined it in the HTML file manually. The answer to this isn't 'define it in the Form class. I have for example other HTML widgets that are to going to play with being shoehorned into a Django Form definition. def AnalyseDoc(request): doctype="" if request.method == "POST": form = AnalyseForm(request.POST, request.FILES) if form.is_valid(): filecontent = request.FILES['filename'] doctype=form.cleaned_data['doctype'] # dummydata=form.cleaned_data['dummydata'] print(dummydata) analyse = analyseStuff(file=filecontent,doctype=doctype, dummydata=dummydata) else: form = AnalyseForm() return render( request, "summary.html", { "dummydata": "x", "form": form, 'filecontent': filecontent, "doctype": doctype, }, ) This is a bit of a quandry <h1>What file would you like to Analyse?</h1> <form action = "" method = "post" enctype="multipart/form-data"> <div class="form-check form-switch"> <label class="form-check-label" for="dummydata">Use Dummy Data</label> <input class="form-check-input" type="checkbox" role="switch" id="dummydata" checked> </div> {% csrf_token %} {{form | crispy}} <button id="submit" type="submit" class="btn btn-primary">Analyse<button> … -
How to Implement Media File Upload Limits and Through Models in Django API for Large Real Estate File Management System?
I am building a large real estate file management system using Django API. I have created a separate app for media handling, and in my model, I want to enforce the following limits: A single featured image A gallery with a maximum of 10 images A maximum of 2 video uploads, each with a cover image A maximum of 2 music files A maximum of 2 PDF files For these, I've used a Through Model to connect the media model to the main model, such as a "listing" or "project" model. My question is: Should these upload limits be handled within the Django serializer, or is there a better approach? Is this the best way to connect models, especially when the main models might have multiple foreign keys? I’m concerned about performance and scalability. Since speed is critical and I need to connect media to models across multiple apps, what would be the most efficient way to implement these restrictions? Thanks in advance! my code : Model.py from django.db import models from django.core.validators import FileExtensionValidator import os from django.utils.translation import gettext_lazy as _ import uuid from django.core.exceptions import ValidationError from src.core.models.base import BaseModel def upload_media_path(instance, filename): ext = filename.split('.')[-1].lower() return … -
Why is my Django serializer returning only Match data and not including related Score data in the API response?
I'm working with Django REST Framework and trying to create an API endpoint that returns live match details along with their associated scores. I have two models, Match and Score, where Score has is associated with Match with a foreignkey. However, when I serialize the Match model, the response only includes match details and does not include any score information. Here’s what my serializers look like: class ScoreSerializer(serializers.ModelSerializer): class Meta: model = Score fields = ['id', 'run', 'wickets', 'overs'] class MatchSerializer(serializers.ModelSerializer): scores = ScoreSerializer(many=True, read_only=True) class Meta: model = Match fields = '__all__' Here is my view code: def livematch(request): live_matches = Match.objects.filter(match_mode='Live') serializer = MatchSerializer(live_matches, many=True) return Response({'success': True, 'data': serializer.data}) -
How to structure a Django DRF project for handling multiple tests and responses
I am working on a Django project using Django REST Framework (DRF), where I need to define a list of tests. Each test consists of multiple questions, and there are corresponding answers for those questions. My initial idea is to create an app called tests and use two CSV files: One CSV file containing all the questions for different tests. Another CSV file containing all the answers. However, I am concerned that this approach might make the code confusing and difficult to maintain. Questions: What is the best architecture for implementing this feature in Django DRF? Is storing test questions and answers in CSV files a good approach, or should I use models and a database instead? If there are any existing similar open-source projects on GitHub, could you provide references? I would appreciate any guidance or best practices on how to structure this project effectively. -
Chaining filter with django filter and django autocomplete light
I am trying to combine Django Filters (DF) with Django Autocomplete Light (DAL). I also want to chain the filter on a few fields in my model. For instance, before applying the DF to my model, I'd like to accomplish the following: Select a certain country. Filter all regions within the selected country. Filter all the cities within the selected region. I have implemented DF and DAL separately and have no issues, which indicates that my views are working as intended. Therefor I don't see any point to share the URLs. I can the see the following response in the console when manually testing DAL in another form: This means that the forwarding in DAL works. However, when I try DF together with DAL: I see that the dictionary values are not set. Which is correct because in the drop-down form I don't see any filtering. I can only auto complete my search for the country field. The region and city fields are not working properly. Views: class CountryAutoComplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Country.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs class RegionAutoComplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Region.objects.all() country = self.forwarded.get("country", None) if country: qs = qs.filter(country=country) if self.q: qs … -
Django translation for uz-cyrl return uz instead
I have configured my django LANGUAGES like import os from django.utils.translation import gettext_lazy as \_ from config.settings.base import BASE_DIR LANGUAGE_CODE = "en" USE_I18N = True LANGUAGES = ( ("uz", _("Uzbek")), ("uz-cyrl", _("Cyrillic")), ("ru", _("Russian")), ("en", _("English")), ("ar", _("Arabic")), ) LOCALE_PATHS = [os.path.join(BASE_DIR, "locale")] I have translated texts in all .po files and compiled them. In local runserver it works with Accept-Language: uz-cyrl properly, but through docker-compose it returns uz translation instead, what might be the reason? I have used different base docker images like python3.11-slim, python3.11 itself but not worked. -
How to Migrate from LDAP to LDAPS in a Django Application?
I'm currently using Django with django-auth-ldap for authentication, and my organization is transitioning from LDAP to LDAPS for security reasons. I need to update my Django settings to use LDAPS instead of LDAP, but I'm unsure of the exact steps required. Here’s my current configuration: AUTH_LDAP_SERVER_URI = "ldap://abc.example.com" AUTH_LDAP_BIND_DN = "cn=admin,dc=example,dc=com" AUTH_LDAP_BIND_PASSWORD = "password" AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=users,dc=example,dc=com", ldap.SCOPE_SUBTREE, "(uid=%(user)s)") I understand that for LDAPS, I need to change AUTH_LDAP_SERVER_URI to ldaps://abc.example.com:636, but I have a few questions: What other changes are required in Django settings? Do I need to configure SSL certificates for django-auth-ldap to work with LDAPS? If so, how? -
VSCode Ignores Mypy Type Hints When Using Django Plugins
I'm using VSCode and mypy in my Django project. My pyproject.toml configuration looks like this (following the Django Stubs README): [tool.mypy] mypy_path = "." python_version = "3.13" strict = true plugins = ["mypy_django_plugin.main"] [tool.django-stubs] django_settings_module = "conf.settings" When I run mypy in the terminal, everything works fine, and I get proper type checking. However, in VSCode, I don't get any type hints at all. If I comment out the plugins line, mypy starts working in VSCode again. What I've Tried: Running mypy manually in the terminal → Works as expected Commenting out plugins → VSCode starts showing hints again Checking that VSCode uses the correct mypy config (it's picking up pyproject.toml) Any insights would be greatly appreciated! -
ANPR OpenCV PyTesseract Python Code not working
Crappy coder needs help with code. Began work on a Python Script for an Automated License Plate Recognition system on a Raspberry Pi. The intended goal of it is to derive a plate from an image, read the text and download to a file. The text is then displayed on a HTML webpage connected via Django Framework. I've been told to change from PyTesseract to a different OCR model but I'm too far into the project to really change anything substantially. I'm not sure what's going wrong specifically with the code so any input is appreciated. import cv2 import pytesseract import os import datetime import numpy as np # Directory to save images IMAGE_DIR = "captured_plates" if not os.path.exists(IMAGE_DIR): os.makedirs(IMAGE_DIR) # File paths ARRIVED_FILE = "arrived.txt" LEFT_FILE = "left.txt" # Open the camera cap = cv2.VideoCapture(0) def preprocess_image(image): """Convert image to grayscale, blur, and apply adaptive thresholding.""" gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) blurred = cv2.GaussianBlur(gray, (5, 5), 0) edged = cv2.Canny(blurred, 100, 200) # Edge detection return edged def find_license_plate(image): """Detect contours and extract the region most likely to be the license plate.""" processed = preprocess_image(image) contours, _ = cv2.findContours(processed, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) possible_plates = [] for contour in contours: x, y, … -
no such column: polls_question.question_text?
Step:1 Use THis Command python manage.py dbshell If you're using SQLite, you can use the dbshell to interact directly with the database and check if the column question_text exists in the polls_question table. If it doesn't exist, there was likely an issue with the migration. Step:2 Then, in the shell, you can run the following query: PRAGMA table_info(polls_question); This will list all the columns in the polls_question table, and you can check if question_text is listed. Step:3 If the column is not there: If the question_text column is not visible, it means that your migration has not been applied correctly, or for some reason, the database has not been updated properly. In this case, you will need to run the migration again, as mentioned earlier. You need to run python manage.py makemigrations and python manage.py migrate to update the database. Step:4 Run the Application After Fixes Once you’ve confirmed that the migration has been applied correctly and the model matches the database, try accessing your application again and check if the error persists. What I tried in my previous explanation was to provide a step-by-step guide on how to troubleshoot the issue with the polls_question.question_text column not being found in … -
xml UBL2.1 invoice error python , using django block template
I got this error when i tried to check validity of xml invoice Error in an electronic invoice in UBL (Universal Business Language) format that relates to compliance with billing requirements, so here I'm using django block template that function call to create xml files from invoices depending on ubl 2.1 , i got error when I'm trying to check validity of xml invoice ... could any one help here is the code of the template {% comment %} {% for discount in %} {% endcomment %} {% if invoice.allowance_discount %} <cac:AllowanceCharge> <cbc:ID>1</cbc:ID> <cbc:ChargeIndicator>false</cbc:ChargeIndicator> <cbc:AllowanceChargeReason>discount</cbc:AllowanceChargeReason> <cbc:Amount currencyID="{{ invoice.currency.code }}">{{ invoice.allowance_discount|default:"0.0"|floatformat:2 }}</cbc:Amount> <cac:TaxCategory> <cbc:ID schemeAgencyID="6" schemeID="UN/ECE 5305">{{ invoice.company.finance_company.account_sale_tax.vat_category_code }}</cbc:ID> <cbc:Percent>{{ invoice.company.finance_company.account_sale_tax.amount|default:"0.0"|floatformat:2 }}</cbc:Percent> <cac:TaxScheme> <cbc:ID schemeAgencyID="6" schemeID="UN/ECE 5153">VAT</cbc:ID> </cac:TaxScheme> </cac:TaxCategory> </cac:AllowanceCharge> {% endif %} {% comment %} {% endfor %} {% endcomment %}` ``` here is the error and warning i got `Errors category : BR_ERROR code :BR-CL-18 message : Invoice tax categories MUST be coded using UNCL5305 code list Warnings category : BR_KSA_WARNING code :BR-KSA-80 message : The Pre-Paid amount (BT-113) must be equal to the sum total of the Prepayment VAT category Taxable Amount (KSA-31) and the Prepayment VAT Category Tax Amount (KSA-32). category : BR_KSA_WARNING code :BR-KSA-08 message : … -
Database not connecting
I have tried different databases with my Django projects but it's not connecting.The railway connection is showing " could not translate host name"postgress.railway.internal"" While the supabase is showing same thing. No such host is known I have made sure the credentials are correct expecting the tables to be created once I do my migration but it doesn't -
django-allauth: enforce policies for certain users
I'm looking to implement django-allauth for an existing project, mainly to add OTP and SSO. I have an SPA so I would need the allauth API as documented here. However, since this requires quite a lot of refactoring I'm a bit hesitant to just throw this app in there, and I can't really tell if it's possible to do what I want from just the documentation. Depending on the Organization a user belongs to (or is invited to), there might be different requirements. I need to be able to enforce OTP or SSO (from a specific provider), but only for certain users. This applies to both existing and new users. Example flows: New user is invited to an organization with OTP enforcement User signs up User accepts invite User is forced to setup OTP because of organization policy New user is invited to an organization with SSO enforcement Because of SSO, user can only sign up with specific SSO An organization adds the enforcement of OTP for their users Any existing organization user that logs in will have to setup OTP before continuing Existing user is invited to organization with policy User logs in User accepts invite User is forced … -
I encountered an AUTH_USER_MODEL error while trying to populate my database with fake data?
I wanted to populate my database for testing purposes, so after doing some research, I came across a tool called FactoryBoy. I decided to use it in conjunction with Pandas to extract data from a CSV file and load it into my database. After writing the code, I gave it a try. Initially, I faced some configuration issues, particularly with defining the correct path, as I was running the script directly without using manage.py. Eventually, I encountered an error that I couldn’t resolve, as I couldn't define the source. django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'users.User' that has not been installed I added the users module to the INSTALLED_APPS environment variable, but I'm still encountering this error. Do you have any suggestions on how to fix it? -
Django : 'empty_form' is not used in polymorphic formsets, use 'empty_forms' instead
I am newbie at Python/Django i have been charged to migrate old project from Python 3.7 / Django 2.2.5 to the Python 3.12 and Django 5.1 but when i did this some functionality didn't work now . For exemple before i have in the Admin interface when i click on "Add watcher" i can create watcher and in the same page choose the realted Trigger, Indicator and other staff. But in my new version when i choose Add Watcher i have this error : RuntimeError at /admin/watchers/watcher/add/ 'empty_form' is not used in polymorphic formsets, use 'empty_forms' instead. I am using the last version of django-polymorphic, nested-admin , I know that django-polymorphic is listed as only supporting Django versions 2.2, 3.0, 3.1, 3.2 and 4.0. It does not support Django version 5.1 , I tried the a later version using pip install git+https://github.com/jazzband/django-polymorphic.git@v4.0.0a#egg=django-polymorphic and also Django 4.x i got the same error: from polymorphic.admin import PolymorphicParentModelAdmin, PolymorphicChildModelAdmin, PolymorphicInlineSupportMixin import nested_admin from django.db import transaction from watchers.models import * class TriggerInline(nested_admin.NestedStackedPolymorphicInline): model = apps.get_model('triggers', 'Trigger') child_inlines = tuple([type(f'{subclass.__name__}Inline', (nested_admin.NestedStackedPolymorphicInline.Child,), { 'model': subclass, 'inlines': [ TriggerComponentInline] if subclass.__name__ == "CompositeTrigger" else [] }) for subclass in apps.get_model('triggers', 'Trigger').__subclasses__()]) #Same that TriggerInline class IndicatorInline(nested_admin.NestedStackedPolymorphicInline) … -
Django TemplateDoesNotExist error for Jinja2 template (dashboard.jinja)
I'm trying to use Jinja2 templates in my Django project, but I'm getting the following error when accessing the / (dashboard) page: TemplateDoesNotExist at / dashboard.jinja My Setup: Settings (app/settings.py) I have configured Jinja2 as the template backend: TEMPLATES = [ { 'BACKEND': 'django.template.backends.jinja2.Jinja2', "DIRS": [BASE_DIR / "core/templates"], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Template Location (app/authentication/templates/dashboard.jinja) {% extends 'core/layouts/main.html' %} {% block title %}Dashboard | {% endblock %} {% block content %} <h2>Welcome, {{ user.name }}</h2> <a href="{% url 'logout' %}">Logout</a> {% endblock %} View (app/authentication/views.py) @login_required def dashboard(request): return render(request, "dashboard.jinja", {"user": request.user}) Issue: The file dashboard.jinja exists in app/authentication/templates/, but Django is unable to find it. I'm not sure if my TEMPLATES settings are correct for Jinja2. I expected render(request, "dashboard.jinja") to find the file, but it throws TemplateDoesNotExist. What I’ve Tried: Ensured the file exists in app/authentication/templates/. Checked that the TEMPLATES["DIRS"] path is correct (core/templates). Tried moving dashboard.jinja to core/templates/ to see if it gets detected. Question: How can I correctly configure Django to find my Jinja2 template inside app/authentication/templates/? Do I need to modify TEMPLATES['DIRS'], or should I use a different approach? Any help would be appreciated! -
How to conditionally modify the <title> tag in Django templates?
I have a base template (main.html) with the following code for the tag: main.html: <title>{% block title %}{% endblock %} | Application</title> In a child template (dashboard.html), I override the title block like this: dashboard.html: {% extends 'main.html' %} {% block title %}Dashboard{% endblock %} If the title block is not overridden in the child template, I want the title to just be Application, without the extra | Application. How can I check if the block is overridden and modify the title accordingly? When I pass the title block from the child template like this: {% extends 'main.html' %} {% block title %}Dashboard{% endblock %} Then I need the title to display as "Dashboard | Application". If I don't pass the title block: {% extends 'main.html' %} Then the title should just be "Application". -
How to check if a Django template block is overridden in the child template?
I am working on a Django project where I have a base layout template (main.html) and a child template (dashboard.html). I want to modify the tag so that if the child template provides a title, it should be formatted as: Page Title | Application Otherwise, if the block is empty or not overridden, it should just be: Application (without the extra | Application). Here’s my main.html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title> {% block title %}{% endblock %}{% if block.super %} | Application{% endif %} </title> <link rel="stylesheet" href="{% static 'assets/css/style.css' %}"> </head> <body> {% block content %}{% endblock %} </body> </html> And here’s my dashboard.html: {% extends 'core/layouts/main.html' %} {% block title %}Dashboard{% endblock %} {% block content %} <h2>Welcome, {{ user.name }}</h2> <a href="{% url 'logout' %}">Logout</a> {% endblock %} Issue: When the child template doesn't override the title block, the output is: | Application Instead of just: Application How can I check whether a block is overridden in the child template and adjust the title accordingly? Would appreciate any suggestions. Thanks!