Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
My Django Project is sending the same email from different apps
I have a Django Project with two different apps: contact_us and booking. both are forms on different sections of the site. when the form for booking request is being sent it saves the info to the table and it is sending a confirmation email... the problem is that the content of the email is from the contact_us view... it is sending from the same email account but the content should be different. From Contact i get the email with Contact info, i added logs everywhere to see where the error is but is not giving me any clues except that contact_us might be overwriting booking at some point my settings are like this: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'host' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'email@email.com' EMAIL_HOST_PASSWORD = 'password' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER public_pages views.py def contact_us(request): logger.debug("Request method: %s", request.method) if request.method == 'POST': logger.debug("Form data received: %s", request.POST) form = ContactForm(request.POST) if form.is_valid(): logger.debug("Form is valid") contact = form.save() # Save the form data to the ContactUs model logger.debug("Contact saved: %s", contact) try: # Send email to the user send_mail( 'We Received Your Message', f'Thank you for contacting us, {contact.name}. We will review your message shortly.', settings.DEFAULT_FROM_EMAIL, … -
Django Cloud Storage NoSuchKey
I deploy a Django/React project with GKE, Cloud SQL as DB, Cloud Storage for static file. When I trying upload files(both by Django admin and API), the url I get always tells me This XML file does not appear to have any style information associated with it. The document tree is shown below. <Error> <Code>NoSuchKey</Code> <Message>The specified key does not exist.</Message> <Details>No such object: my-bucket/media/uploads/01.JPG</Details> </Error> I tryed directly upload file in GCP console and file can be visited. Also when I use gsutil cp .gitignore gs://my-bucket/media/ file can be visited. below are my settings.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/5.1/howto/static-files/ DEFAULT_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' STATICFILES_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' GS_BUCKET_NAME = 'my-bucket' GS_MEDIA_BUCKET_NAME = 'my-bucket' GS_DEFAULT_ACL = 'publicRead' GS_FILE_OVERWRITE = False # STATIC_ROOT = '/app/static' STATIC_URL = f"https://storage.googleapis.com/{GS_BUCKET_NAME}/static/" MEDIA_URL = f"https://storage.googleapis.com/{GS_MEDIA_BUCKET_NAME}/media/" and deployment.yaml apiVersion: apps/v1 kind: Deployment metadata: name: app spec: replicas: 2 selector: matchLabels: app: app template: metadata: labels: app: app spec: serviceAccountName: my-service-account containers: - name: app image: asia-east1-docker.pkg.dev/my-project-id/app/backend:latest ports: - containerPort: 8000 env: - name: DB_USER - name: DB_PASSWORD - name: DB_NAME - name: DB_HOST - name: DB_PORT resources: requests: memory: "512Mi" cpu: "500m" limits: memory: "1Gi" cpu: "1" - name: cloud-sql-proxy image: gcr.io/cloud-sql-connectors/cloud-sql-proxy:latest args: volumeMounts: - … -
Cannot assign requested address: when sending e-mail from Django Docker container
I have this error message, when sending an e-mail from Django Docker container. OSError at /accounts/signup/ [Errno 99] Cannot assign requested address Request Method: POST Request URL: http://127.0.0.1:8000/accounts/signup/ Django Version: 4.0.10 Exception Type: OSError Exception Value: [Errno 99] Cannot assign requested address Exception Location: /usr/local/lib/python3.10/socket.py, line 833, in create_connection Python Executable: /usr/local/bin/python Python Version: 3.10.4 Python Path: ['/code', '/usr/local/lib/python310.zip', '/usr/local/lib/python3.10', '/usr/local/lib/python3.10/lib-dynload', '/usr/local/lib/python3.10/site-packages'] Here is my configuration in settings.py EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" DEFAULT_FROM_EMAIL = "my@gmail.com" EMAIL_HOST = "smtp.gmail.com" EMAIL_PORT = 465 EMAIL_USE_SSL = True EMAIL_USE_TLS = False EMAIL_HOST_USER = "my@gmail.com" EMAIL_HOST_PASSWORD = "mypassword" Here is docker-compose.yml. version: "3.9" services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db environment: - "DJANGO_SECRET_KEY=my_key" - "DJANGO_DEBUG=True" db: image: postgres:13 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - "POSTGRES_HOST_AUTH_METHOD=trust" volumes: postgres_data: I'm able to send e-mail with the same config via Python code without docker container. -
webrtc shows extra stream with only one peer connection
I am trying to allow my webrtc video call meeting app have multiple peer connections and have the stream appear on the remote video call dynamically using javascript. I have only two tabs in two windows open on the video test room url. One is incognito and one is regular google chrome browser but both are google chrome browsers. They are both logged in to superusers. The problem is, the remote videos are shown twice of the same user of the remote user. This is my video call html file. <!DOCTYPE html> <html> <head> <style> button { border: 0; background-color: orange; padding: 10px; color: white; border-radius: 7px; } video { border-radius: 15px; } .videoContainer { display: flex; margin: 20px; width: 640px; } .videoContainer h2 { color: white; position: relative; bottom: -380px; left: -350px; width: max-content; } #meet { display: flex; } #recordButton.recording { background-color: red; } #downloadButton { background-color: #4caf50; } button:disabled { background-color: #cccccc; cursor: not-allowed; } </style> <title>A Free Bird Video Call</title> <script src="https://meet.jit.si/external_api.js"></script> </head> <body> <div id="meet"> <div id="remote-videos"> <div class="videoContainer"> <video id="localVideo" autoplay playsinline></video> <h2>{{ request.user.full_name }}</h2> </div> </div> <!-- <div class="videoContainer"> <video id="remoteVideo" autoplay playsinline></video> <h2></h2> </div> --> </div> <div> <button onclick="startCall()">Start Call</button> <button id="recordButton" … -
Google OAuth 2.0: Login with Google works on localhost, but it doesn't work on hosting
I have a small Django website, and I've connected OAuth 2.0. It worked just fine on localhost. (In the Google Console, the authorized redirect URIs were: URI 1: http://127.0.0.1:8000/ URI 2: http://127.0.0.1:8000/google/login/callback/) Now I have moved the website to hosting and changed the URLs to: URI 1: https://yukkiewqr.eu.pythonanywhere.com/ URI 2: https://yukkiewqr.eu.pythonanywhere.com/google/login/callback/ However, when I'm trying to log in through Google, I see the following error: "Access blocked: This app’s request is invalid. You can’t sign in because this app sent an invalid request. You can try again later or contact the developer about this issue. Learn more about this error. If you are a developer of this app, see error details. Error 400: redirect_uri_mismatch." On my website, I am using the Django Framework and the AllAuth plugin to connect to Google. I would be very grateful if anyone knows how to fix it -
Why is my email template in Django sending the whole model and not just the values input
I'm trying to email a copy of my contact form when the form is saved, but the template tags seem to be pulling the full model not just the inputs. I have no idea what I'm doing wrong here. My email template.txt file Hi! You received a message from {{ contact_form.name }} at {{ contact_form.email }} {{ contact_form.message}} My views.py if request.method == "POST": contact_form = ContactForm(request.POST, request.FILES) if contact_form.is_valid(): contact_form.save(commit=False) try: contact_form.image_field_1 = request.FILES['image_field_1'] except: contact_form.save() try: contact_form.image_field_2 = request.FILES['image_field_2'] except: contact_form.save() contact_form.save() subject = 'Website enquiry' body = render_to_string( 'contact_emails/contact_email_body.txt', {'contact_form': contact_form, }) send_mail( subject, body, settings.DEFAULT_FROM_EMAIL, ['test@gmail.com'], ) messages.success(request, "Message received! \ We will respond as soon as possible!") else: contact_form = ContactForm() This is what arrives in the email Hi! You received a message from at Testing again -
Asyncio coroutine execution stopped and didn't return any error
I'm facing an odd behavior on one of my applications. So I have an application that has an POST entrypoint that receives a list of order id's and after processing each order it must inform an external API about the monetary value of each order. So what we did was the following: round_details_tasks = [ asyncio.create_task( self.launch_individual_order_details(order), name=f"task_order_{order.id}", ) for order in active_orders ] results = await asyncio.gather(*order_details_tasks, return_exceptions=True) for task, result in zip(order_details_tasks, results): if isinstance(result, Exception): print(f"⚠️ Task '{task.get_name()}' raised an exception: {result}") else: print(f"✅ Task '{task.get_name()}' succeeded with result: {result}") The launch_individual_order_details(order) function does the following stuff and other non I/O logic before this block: logger.debug(f"Sending order details with success for order: {order.id}") await order_service.send_order_request(order) Inside send_order_request we create a entry on a table called Transaction with the order id and the corresponding order amount and in pending state and send http request using aiohttp.CLient library. Afterwards we update the transaction status to Success if the request response is succesful and to error if the request fails. So the problem we are facing is that when our system is with a relative amount of load in our pods when the pod uses 70% of the CPU limits … -
User getting added to multiple permission groups instead of the one
In my application, when a user registers, they are identified as either a lecturer or a student. These are categorised as auth_groups, and users are assigned to one with these methods... def register_student(self, data): user = User.objects.create( user_id = data["user_id"] ) students_group = Group.objects.get(name = "students") user.groups.add(students_group) return user def register_lecturer(self, data): user = User.objects.create( user_id = data["user_id"] ) lecturers_group = Group.objects.get(name = "lecturers") user.groups.add(lecturers_group) return user On the surface, this appeared to work fine, but when I went to write the test suite, the following issue occurred: When register_student is called, the user is added to both the lecturer and student groups in the line user.groups.add(students_group). I want to mention that "students" have more permissions than "lecturers". Why is this happening? Thank you for any help! -
How to Restart a Django App via API After Modifying settings.py?
I am working on a Django project where I dynamically add new languages via an API. The workflow is as follows: Add a new language via the API (http://localhost:8000/core/swagger/). Via API /generate/ Generate the .mo and .po files after adding the language. The new language is added to languages.json, which is loaded into settings.py at startup. To apply the new language, Django needs to be restarted. I have tried several approaches to restart Django automatically via an API: ✅ Clearing Django's cache before restarting. ✅ Using a .sh script to kill the process and restart Django. ✅ Manually stopping and restarting Django (this works fine manually, but not via the script). Issue: When calling the restart API, Django stops successfully but does not restart. The restart only works when I manually stop the server and restart it from the terminal. The script kills the PID but doesn’t properly relaunch Django. What I Need Help With: What is the best way to restart Django from within an API call? Is there a more reliable way to restart Django inside Docker as well? Why does manually stopping Django and then restarting work, but the script approach does not? Relevant Repo with explaination … -
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 …