Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - PostgreSQL docker - authentication issue
I've been trying to set up my first Django and PostgreSQL project with Docker containers. I followed this setup and everything went as expected: https://learndjango.com/tutorials/django-docker-and-postgresql-tutorial Opening my Django admin portal worked without any issues on: http://127.0.0.1:8000/admin/ However I also wanted to connect to my 'db' (via DBeaver or in the terminal). However, I keep getting this error: FATAL: password authentication failed for user "postgres" FATAL: password authentication failed for user "postgres" Does anyone have any experience with this issue? DBeaver connection docker-compose.yml settings.py I first tried to only have my PostgresQL database in docker and keep the Django project outside, locally. However, that was the first time I bumped into the issue of 'password authentication'. I figured it was because I didn't set up both the Django project and my PostgresQL in Docker containers. But unfortunately, adding both in Docker containers did not help. I also tried to: Change the pg_hba.conf authentication Method to 'host all all all md5' instead of 'host all all all scram-sha-256'. But that didn't do anything either. -
heroku django Spatilite Unable to load the SpatiaLite library extension
Hi I get error while i'm trying to run my application on heroku with Spatialite: Unable to load the SpatiaLite library extension. Library names tried: mod_spatialite.so, mod_spatialite. my settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # 'ENGINE':'django.contrib.gis.db.backends.postgis', # 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } django_heroku.settings(locals()) # geodjango=True if DATABASES['default']['ENGINE'] in ('django.db.backends.postgresql', 'django.db.backends.postgresql_psycopg2'): DATABASES['default']['ENGINE'] = 'django.contrib.gis.db.backends.postgis' elif DATABASES['default']['ENGINE'] == 'django.db.backends.sqlite3': DATABASES['default']['ENGINE'] = 'django.contrib.gis.db.backends.spatialite' -
Wagtail admin preview panel not working in production
The page preview in the Wagtail admin is working fine locally on my dev server, but in production, the preview is not displayed, just a spinning wheel. In the Chrome dev tools console, I see the error message: Uncaught SecurityError: Failed to read a named property 'scroll' from 'Window': Blocked a frame with origin "https://example.com" from accessing a cross-origin frame. where I replaced my actual domain by "example.com". In production, I'm using Wagtail 6 with nginx and gunicorn, serving media and static files from the same server. Here are the relevant parts of my nginx config, with some data XXXXed out: upstream app_server { server unix:/opt/example-com/gunicorn.socket fail_timeout=0; } server { listen 80; server_name example.com; rewrite ^/(.*) https://example.com/$1 permanent; } server { listen 443 ssl; server_name example.com; client_max_body_size 50M; ssl_certificate XXXX ssl_certificate_key XXXX location /static/ { alias /opt/example-com/static/; } location /media/ { alias /opt/example-com/media/; } location / { include proxy_params; proxy_pass http://unix:/opt/example-com/gunicorn.socket; } location /admin/ { include proxy_params; proxy_pass http://unix:/opt/example-com/gunicorn.socket; } } In the base settings, I have set WAGTAILADMIN_BASE_URL = "https://example.com" and on /admin/sites/, the have set the site hostname to "example.com". I'm not sure why I'm running into this cross-site thing at all, and how to fix it. -
BooleanField form Checkboxes always empty in Django
I have a Model form that has some checkboxes. The database has values for these records for all rows. My form displays with empty checkboxes all the time. I can submit values via the checkbox and the database updates correctly, but form still shows empty checkboxes. What am I missing here? Model definition contains is_coach = models.BooleanField(default=False, blank=True) is_parent = models.BooleanField(default=False, blank=True) is_committee = models.BooleanField(default=False, blank=True) Form is forms.ModelForm containing is_committee = forms.BooleanField(required=False) is_coach = forms.BooleanField(required=False) is_parent = forms.BooleanField(required=False) HTML template contains <form action="{% url 'user_profile_admin' %}" method="post"> {% csrf_token %}{{ form|crispy}} <button type="submit" class="btn btn-success">Update</button> <button type="button" onclick="window.location='members';return false;"class="btn btn-danger">Cancel</button> </form> Link to screenshot showing checkboxes -
Django Returning http instead of HTTPS in Prod
I deployed a Django app in an Ec2 with gunicorn and nginx but links generated by django are http instead of HTTPS. I have included the necessary settings. For example, when I have paginations, I got count": 12, "next": "http://my.example.com/article/?page=2", "previous": null, Instead of count": 12, "next": "https://example.com/journal/?page=2", "previous": null, All the links are like this, although they got redirected when you click on them or copy them in the browser but it is showing a funny reaction in the frontend My DNS is being managed by cloudfare and everything seem to be fine there. #In settings SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') USE_X_FORWARDED_HOST = True #My nginx file server { listen 80; server_name fronend.example.com; location / { autoindex on; root /home/ubuntu/frontend/dist/frontend; try_files $uri $uri/ /index.html; } } # Backend Nginx Config server { listen 80; server_name backend.example.com; location = /favicon.ico { access_log off; log_not_found off; } location /staticfiles/ { alias /home/ubuntu/backend/static; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; # proxy_set_header Host $host; #I commented these out when I was troubleshootng # proxy_set_header X-Real-IP $remote_addr; # proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/backend.example.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/backend.example.com/privkey.pem; # managed by … -
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 …