Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Git like view for dataframe comparison
I have two dataframe set called df1 and df2. I need to create a view in django template to compare these two dataframe in side by side. It should be looks like the git like comparison like below. I have tried the below but didn't work views.py # Convert DataFrames to lists of dictionaries for easier iteration df1_data = df1.to_dict(orient='records') df2_data = df2.to_dict(orient='records') # Combine the data to be passed to the template combined_data = list(zip(df1_data, df2_data)) return render(request, self.view_template,{ 'combined_data': combined_data } ) template {% block content %} <style> .row { display: flex; flex-direction: row; justify-content: space-between; } .column { flex: 1; } </style> <div class="container"> {% for row1, row2 in combined_data %} <div class="row"> <div class="column"> {% for key, value in row1.items %} <p>{{ key }}: {{ value }}</p> {% endfor %} </div> <div class="column"> {% for key, value in row2.items %} <p>{{ key }}: {{ value }}</p> {% endfor %} </div> </div> {% endfor %} </div> {% endblock %} -
weasyprint "Document has no attribute write_png"
I am writing a webapp in Python and Django. I use weasyprint to write pdf documents and I would like to use write_png() to get a png thumbnail of each pdf. This is from my views.py: pdf_letter = weasyprint.HTML(string=letter, base_url=static_url).render( stylesheets=[weasyprint.CSS(static_url + "/abrechnung/css/print-portrait.css")] ) pdf_table = weasyprint.HTML(string=table).render( stylesheets=[weasyprint.CSS(static_url + "/abrechnung/css/print-landscape.css")] ) val = [] for doc in pdf_letter, pdf_table: for p in doc.pages: val.append(p) pdf_file = pdf_letter.copy(val).write_pdf(f"{datetime.now()}.pdf") thumbnail = pdf_letter.copy(val).write_png(f"{datetime.now()}.png") When I try to run the program, I get the following error message in the browser: 'Document' object has no attribute 'write_png' pdf_file = pdf_letter.copy(val).write_pdf(f"{datetime.now()}.pdf") thumbnail = pdf_letter.copy(val).write_png(f"{datetime.now()}.png") ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The weasyprint documentation on the write_png() function can be found here: https://doc.courtbouillon.org/weasyprint/v52.5/api.html#weasyprint.document.Document.write_png As I read the weasyprint documentation, I states that weasyprint.HTML.render() produces a weasyprint.document.Document. Said object has a function write_png(). Soooo.... WTF? What am I doing wrong here? I tried this for i, page in enumerate(document.pages): document.copy([page]).write_png('page_%s.png' % i) and this for page in document.pages: yield document.copy([page]).write_png() from the weasyprint tutorial (variables etc. adapted to my code of course) but none of both worked - I got the same error. Writing the pdf file alone is no problem, it is saved and returned later on. Problems just started when I … -
'svc_payment_dev'. The domain name provided is not valid according to RFC 1034/1035
Upon sending requests to the dockerized Django app through the API gateway layer using the container name (svc_payment_dev), I faced an issue indicating that the domain name provided is not valid acoarding to RFC 1034/1035 I know that underscores are typically not allowed in hostnames, and unfortunately, I'm unable to modify the container name at this time.So. I'm currently seeking a solution to modify the validation hostname in Django. Also, I've added the hostname to ALLOWED_HOSTS list but still encounter the "invalid hostname" error. ALLOWED_HOSTS = [ 'svc_payment_dev:8000' ] -
Nginx and SSL configuration inside docker container is not working
Am using following nginx conf file : server { listen 80; server_name domain; # Redirect HTTP to HTTPS return 301 https://$host$request_uri; } server { listen 443 ssl; server_name localhost; ssl_certificate /etc/nginx/cert/ddomain.crt; ssl_certificate_key /etc/nginx/cert/domain.key; location / { proxy_pass http://0.0.0.0:8000; proxy_set_header Host $host; 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; } } I am using the following docker file to run the container. This container runs 8000 port. FROM python:3.8 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set the working directory in the container WORKDIR /app # Install system dependencies RUN apt-get update && apt-get install -y \ gcc \ gettext \ dbus \ libdbus-1-dev \ libcups2-dev \ libcairo2-dev \ libgirepository1.0-dev \ libgtk-3-dev \ libsecret-1-dev \ pkg-config \ wget \ nginx \ && rm -rf /var/lib/apt/lists/* # Copy the requirements file and install Python dependencies COPY requirements.txt /app/ RUN pip install --no-cache-dir -r requirements.txt # Copy SSL certificate files COPY ssl_certificates/domain.crt /etc/nginx/cert/domain.crt COPY ssl_certificates/domain.key /etc/nginx/cert/domain.key # Copy the Nginx configuration file COPY nginx.conf /etc/nginx/conf.d/default.conf # Copy the rest of the application files COPY . /app/ # Expose port 8000 to allow communication to/from server EXPOSE 8000 # Your application's command to run CMD ["python", "manage.py", "runserver", … -
Nginx gives 403 Forbidden error serving files
I am a newbie to nginx and run into a problem: nginx response with 403 Forbidden when I request example.com/media/ and all files inside the media folder. I am creating web application with python using Django Rest Framework. Here is my nginx file in /etc/nginx/sites-enabled/example.com: server { server_name example.com; access_log /var/log/nginx/example.com-access.log; error_log /var/log/nginx/example.com-error.log; location /media/ { alias /root/spaceai/backend/SpaceAI_Backend/apps/media/; } location / { client_max_body_size 0; gzip off; ## https://github.com/gitlabhq/gitlabhq/issues/694 ## Some requests take more than 30 seconds. proxy_read_timeout 300; proxy_connect_timeout 300; proxy_redirect off; proxy_http_version 1.1; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://localhost:8000; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = example.com) { return 301 https://$host$request_uri; } # managed by Certbot server_name example.com; listen 80; return 404; # managed by Certbot Here is media folder rights: drwxr-xr-x 3 755 root 4096 May Head of /etc/nginx/nginx.conf: user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # … -
DRF Forbidden (CSRF cookie not set.) from React axios POST request
As we know, we don't have access to Django CSRFToken in React by default, So we have to get it somehow. The solution was make a URL for receive CSRFToken in Response-Headers and set csrftoken cookie in browser. So I did it => Views.py @method_decorator(ensure_csrf_cookie, name='dispatch') class GetCSRFToken(APIView): permission_classes = (permissions.AllowAny, ) def get(self, request, format=None): return Response("CSRF cookie set.") CSRFToken.jsx import React, { useState, useEffect} from 'react'; import axios from 'axios'; export default function CSRFToken(){ useEffect(()=>{ const fetchData = async () => { try { const url = 'http://localhost:8000/csrf_cookie' const response = await axios.get(url,{ withCredentials: true, }).then(()=>{ console.log("CSRF Cookie set.") }) } catch (error) { console.error('Error fetching data:', error); } }; fetchData(); }, []); return ( <> </> ) } Result => After that we can access to csrftoken and We can send it through X-CSRFToken Request-Headers. But the problem is when I send the request Django side won't accept that csrftoken and will reject that request. settings.py ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'App.apps.AppConfig' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CSRF_TRUSTED_ORIGINS = ['http://localhost:5173'] Views.py @method_decorator(csrf_protect, name='dispatch') class … -
Avoid app name appending in table name in django
I have implemented database routing in django. I am creating tables in two different database using database routing in django. The issue is app name is appended in database table name. I am using prosgreSql database. I tried to mention db_table with value in class Meta, but it is not working for me. I am expecting only table name in database. I am using prosgreSql database -
disable dark mode in bulma 1.0
I tried disabling the dark mode in my base.css like bulma describes in their docs by adding the @media lines: @media (prefers-color-scheme: light) { :root { } } body { display: flex; min-height: 100vh; flex-direction: column; } ... This is how I import them in my base.html: <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}app{% endblock title %}</title> {% block css %} <link rel="stylesheet" href="{% static 'css/bulma.css' %}"> <link rel="stylesheet" href="{% static 'css/bulma-extensions.min.css' %}"> <link rel="stylesheet" href="{% static 'css/bulma-switch.min.css' %}"> <link href="{% static 'fontawesomefree/css/fontawesome.css' %}" rel="stylesheet" type="text/css"> <link rel="stylesheet" href="{% static 'css/base.css' %}"> {% endblock %} </head> <body> ... </body> </html> I also tried using <body data-theme="light"> but this only affected the footer, and not the content in the body. Also adding the data-theme tag to other elements did not change anything. I want to get rid of darkmode all over the page. How would I do that? Switching the dark mode systemwide to light works though. -
How to debug Okta SAML2 authentication issue in a React + Django application?
I'm integrating Okta SAML2 authentication into my React + Django application. However, despite not encountering any errors, when I attempt to access https://org.okta.com/app/org_lighthousedev_1/exk14dabkz9lmSTEq0x8/sso/saml, it redirects me to https://dev-lighthouse.corporate.org.com/accounts/login/?next=/sso/saml/ instead of completing the SAML authentication flow. I'm unsure how to debug this issue. I'm using djangosaml2==1.9.2 and djangorestframework-simplejwt==5.3.1. Could someone provide guidance or hints on what might be missing by reviewing the code snippet below? These where I gave in okta request for application creation Single sign-on URL https://dev-lighthouse.corporate.org.com/sso/saml/ Recipient URL https://dev-lighthouse.corporate.org.com/sso/saml/ Destination URL https://dev-lighthouse.corporate.org.com/sso/saml/ Audience URI (SP Entity ID) https://dev-lighthouse.corporate.org.com/ Provide details by Okta Team Identity Provider Single Sign-On URL: https://org.okta.com/app/org_lighthousedev_1/exk14dabkz9lmSTEq0x8/sso/saml Identity Provider Issuer: http://www.okta.com/exk14dabkz9lmSTEq0x8 X.509 Certificate:okta.cert.txt IDP metadata : IDP_Metadata.txt Metadata.xml <?xml version="1.0" encoding="UTF-8"?><md:EntityDescriptor entityID="http://www.okta.com/exk14dabkz9lmSTEq0x22328" xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata"><md:IDPSSODescriptor WantAuthnRequestsSigned="false" protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol"><md:KeyDescriptor use="signing"><ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#"><ds:X509Data><ds:X509Certificqate>MIIDojCCAoqgAqeqeqewIBqweqweqeAgIGAY9N9lbIMA0GsfsbfhsbfqwyegqyrqywqqCSqGSIb3DQEBCwUAMIGRMQswCQYDVQQGEwJVUzETMBEG .................. 94nXBpszjEGkSxsAJ1HxEzDdVdDcTRa4YIVGPazKIaiNbNgCha8oGQVgJaXv2EkKFgqhcZeQ0Mfq O7jSBH/M2U7QoTMhj0NhUCdy9ZGwt95TPhpJ8HZ6f0Ynqw+TmsPiRJyp8EVgjyv9weHgeuGk81k3 3JNrh0k2UpnGECHngkDJWGRseXr+zg==</ds:X509Certificate></ds:X509Data></ds:KeyInfo></md:KeyDescriptor><md:NameIDFormat>urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified</md:NameIDFormat><md:NameIDFormat>urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress</md:NameIDFormat><md:SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Location="https://org.okta.com/app/org_lighthousedev_1/exk14dabkz9lmSTEq0x8/sso/saml"/><md:SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" Location="https://org.okta.com/app/org_lighthousedev_1/exk14dabkz9lmSTEq0x8/sso/saml"/></md:IDPSSODescriptor></md:EntityDescriptor> setting.py Django settings for backend project. Generated by 'django-admin startproject' using Django 4.1.7. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.1/ref/settings/ """ from pathlib import Path from dotenv import load_dotenv import os from .saml2.saml_settings import SAML_CONFIG load_dotenv() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # … -
how do i fix the Method not allowed (GET) error in django version 5 [duplicate]
i keep getting this error in logout.html in django everytime i go to it. Here is the code for the logout.html: <form method="post" action="{% url 'logout' %}"> {% csrf_token %} <button type="submit">logout</button></form> here is my views.py code: from django.shortcuts import render, redirect #from django.contrib.auth.forms import UserCreationForm from django.contrib import messages from django.contrib.auth import authenticate,login ,logout from .forms import UserRegisterForm # Create your views here. def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username= form.cleaned_data.get('username') messages.success(request, f'Account created successfully for {username}') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form':form}) def logout(request): logout(request) return redirect('login') here is the urls.py code path('login/',auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/',auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), i expected the site to look like this: https://youtu.be/3aVqWaLjqS4?list=PL-osiE80TeTtoQCKZ03TU5fNfx2UY6U4p&t=970 i am currently following the corey schafer youtube series as shared in the link -
Django settings not reflecting changes [closed]
I have a Django project running on an Ubuntu 22.04 server with Nginx and Gunicorn. After updating the project on my local server, I attempted to transfer it to my cloud server. Using FileZilla, I copied the new files to the server. However, the settings.py file did not update. I made changes to the settings.py file, and then rebooted Gunicorn and Nginx, but the changes did not take effect. I even tried deleting settings.py, but the server still did not respond to the changes. Cache is not enabled. Deleting all the .pyc files did not resolve the issue either. Does anyone know of a solution to this problem? -
How to add custom FileUploadHandler to request in ModelAdmin custom view Django 3.2
I need to add custom file upload handler in admin add and change view (using django 3.2). And getting an error. So far I created custom FileUploadHandler and trying to add to request in my ModelAdmin. Created class in my app\admin.py @admin.register(MyClass) class MyClassAdmin(ModelAdmin): def get_urls(self): urls = super().get_urls() custom_urls = [ url('^my_view/$', self.create_model_view, name='my_view'), ] return custom_urls + urls @csrf_exempt def create_model_view(self, request): request.upload_handlers = [CustomUploadHandler(request)] return super().changeform_view(request) And getting error You cannot set the upload handlers after the upload has been processed. What am i doing wrong? Where request is started processing? -
Django rest framework Status 200 but 'Failed to Load Response Data" On jwt token api
This is the token api of drf jwt. It is giving me 200 but in response it is saying me failed to load data I tried the code in locally it is running in the postman and also the url (https://v2.api.mytask.today/tsauth/api/token/) of server i gave it in the postman it is giving me access and refresh token but in browser it is giving me no response. -
Nginx + Django Static Files issue
I am having an issue with my project. I have everything working in my Django project, when the DEBUG=True in settings.py. But as soon as I change it to False, I get this issue when I go to my website (localhost): Error message with localhost when DEBUG=False Which probably means that either my static files are not correctly sent to my Nginx, or my Nginx web server is not correctly configured to receive/use my static files. Here is the docker-compose I am using: version: '3.8' services: db: image: postgres:13 volumes: - postgres_data:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/app depends_on: - db environment: - DATABASE_URL=postgres://postgres:postgres@db:5432/postgres nginx: build: ./nginx ports: - "80:80" - "443:443" depends_on: - web restart: on-failure # Ensures NGINX retries if it fails to start the first time migrations: build: . command: sh -c "python manage.py makemigrations && python manage.py migrate" depends_on: - db volumes: postgres_data: Dockerfile for my Django project: # Use an official Python runtime as a parent image FROM python:3.9-slim # Set environment varibles ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /app # Install dependencies COPY requirements.txt /app/ RUN pip … -
CSRF cookie doesn't show up in browser cookies after made a request from React to Django and @ensure_csrf_cookie
The question is clear. I made a request from React side to http://localhost:8000/csrf_cookie and my Set_CSRF_CookieView executed in Django side. The response is OK and I'm receiving csrftoken in Response Headers but It won't set on my browser cookies. React port: http://localhost:5173 Django port: http://localhost:8000 You can see csrftoken inside Set-Cookie section of Response Headers: You can see csrftoken cookie is not set on browser cookies My codes => views.py: @method_decorator(ensure_csrf_cookie, name='dispatch') class Set_CSRF_CookieView(APIView): permission_classes = (permissions.AllowAny, ) def get(self, request, format=None): return Response({'success': 'CSRF cookie set.'}) settings.py ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'App.apps.AppConfig' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' # Sessions SESSION_ENGINE = "django.contrib.sessions.backends.signed_cookies" SESSION_COOKIE_NAME = "TDSession" SESSION_COOKIE_HTTPONLY = True # SESSION_SAVE_EVERY_REQUEST = True SESSION_EXPIRE_AT_BROWSER_CLOSE = False SESSION_COOKIE_AGE = 60 * 60 * 24 * 3 CSRF_COOKIE_NAME = 'csrftoken' CSRF_COOKIE_DOMAIN = None CSRF_COOKIE_HTTPONLY = False CSRF_COOKIE_SECURE = False CSRF_COOKIE_SAMESITE = 'Lax' # DRF REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated' ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication' ] } CORS_ORIGIN_ALLOW_ALL = True CSRFToken.jsx import React, { useState, useEffect} from 'react'; import axios from 'axios'; import { useDispatch, useSelector } from 'react-redux'; … -
django get() triggers FOUR queries
During deep debuging i found that simple .get triggers FOUR queries: kwargs['context']['user'] = models.Person.objects.get( pk=16879 ) And postgresql.log prints this: 2024-05-08 10:21:07.913 CEST [3987190] party@partytest LOG: statement: SELECT "structure_persondata"."id", "structure_persondata"."created_at", "structure_persondata"."updated_at", "structure_persondata"."person_id", "structure_persondata"."first_name", "structure_persondata"."middle_name", "structure_persondata"."last_name", "structure_persondata"."pesel", "structure_persondata"."validity_range" FROM "structure_persondata" WHERE ("structure_persondata"."person_id" = 16879 AND "structure_persondata"."validity_range" @> ('2024-05-08T08:21:05.002321+00:00'::timestamptz)::timestamp with time zone) ORDER BY "structure_persondata"."id" ASC LIMIT 1 2024-05-08 10:21:07.927 CEST [3987190] party@partytest LOG: statement: SELECT "structure_persondata"."id", "structure_persondata"."created_at", "structure_persondata"."updated_at", "structure_persondata"."person_id", "structure_persondata"."first_name", "structure_persondata"."middle_name", "structure_persondata"."last_name", "structure_persondata"."pesel", "structure_persondata"."validity_range" FROM "structure_persondata" WHERE ("structure_persondata"."person_id" = 16879 AND "structure_persondata"."validity_range" @> ('2024-05-08T08:21:05.002321+00:00'::timestamptz)::timestamp with time zone) ORDER BY "structure_persondata"."id" ASC LIMIT 1 2024-05-08 10:21:07.937 CEST [3987190] party@partytest LOG: statement: SELECT "structure_persondata"."id", "structure_persondata"."created_at", "structure_persondata"."updated_at", "structure_persondata"."person_id", "structure_persondata"."first_name", "structure_persondata"."middle_name", "structure_persondata"."last_name", "structure_persondata"."pesel", "structure_persondata"."validity_range" FROM "structure_persondata" WHERE ("structure_persondata"."person_id" = 16879 AND "structure_persondata"."validity_range" @> ('2024-05-08T08:21:05.002321+00:00'::timestamptz)::timestamp with time zone) ORDER BY "structure_persondata"."id" ASC LIMIT 1 2024-05-08 10:21:07.946 CEST [3987190] party@partytest LOG: statement: SELECT "structure_persondata"."id", "structure_persondata"."created_at", "structure_persondata"."updated_at", "structure_persondata"."person_id", "structure_persondata"."first_name", "structure_persondata"."middle_name", "structure_persondata"."last_name", "structure_persondata"."pesel", "structure_persondata"."validity_range" FROM "structure_persondata" WHERE ("structure_persondata"."person_id" = 16879 AND "structure_persondata"."validity_range" @> ('2024-05-08T08:21:05.002321+00:00'::timestamptz)::timestamp with time zone) ORDER BY "structure_persondata"."id" ASC LIMIT 1 I thought, that this code is in some loop, but I did this: # raise ValueError('before') kwargs['context']['user'] = models.Person.objects.get( pk=16879 ) raise ValueError('after') first I run this with raise before, and no queries at all, than … -
Cannot get django-admin css file in "Django + nginx + docker"
I could not serve the Django-admin's static files... I think.. It can't not recognize the reverse-proxy path. the location /static/admin/ Literally, The Django static folder is in upstream django server. There is nginx.conf and the inside docker container with django. Please tell me the solution... nginx # nginx upstream react { server 10.180.225.1:3000; } upstream django { server 10.180.226.1:8000; keepalive 100; } server { listen 80; include mime.types; location /static/admin/ { proxy_pass http://django; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location /admin { proxy_pass http://django; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_redirect off; add_header Test "This is for proxy pass."; } location /api { proxy_pass http://django; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_redirect off; proxy_read_timeout 3600s; proxy_connect_timeout 3600s; } location / { proxy_pass http://react; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_redirect off; } } docker exec -it back-web /bin/bash ls... Django Admin page -
Cannot resolved keyword 'date_created' into field
I have a problem with runserver on PowerShell. entries_detail.html: <article> <h2>{{ entry.date_created|date:'Y-m-d H:i' }}</h2> <h3>{{ entry.title }}</h3> <p>{{ entry.content }}</p> </article> entries_list.html: {% for entry in entry_list %} <article> <h2 class="{{ entry.date_created|date:'l' }}"> {{ entry.date_created|date:'Y-m-d H:i' }} </h2> <h3> <a href="{% url 'entry-detail' entry.id %}"> {{ entry.title }} </a> </h3> </article> {% endfor %} views.py: from django.views.generic import ( DetailView, ListView, ) from django.db import models from .models import Entry --- class EntryListView(ListView): model = Entry queryset = Entry.objects.all().order_by("-date_created") class EntryDetailView(DetailView): model = Entry I tried to run python manage.py runserver on PowerShell and I got the result: django.core.exceptions.FieldError: Cannot resolve keyword 'date_created' into field. Choices are: content, data_created, id, title -
how to connect to broker Websocket in django
I am building an algotrading platform, i have access to broker apis and websockets, but i dont know how to connect to broker websocket and consume the data on realtime basis in django I have setup channels: #consumers.py class ChatConsumer(WebsocketConsumer): def connect(self): self.accept() self.external_socket = websocket.WebSocketApp( "wss://api.shoonya.com/NorenWSTP/", on_message=self.on_message, on_error=self.on_error, on_close=self.on_close, ) self.send(text_data=json.dumps({ 'type':'connection_established', 'message':'You are now connected!', })) self.external_socket.run_forever() #routing.py from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/socket-server/', consumers.ChatConsumer.as_asgi()) ] #asgi.py import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack import authengine.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'atkmain.settings') application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': AuthMiddlewareStack( URLRouter( authengine.routing.websocket_urlpatterns ) ) }) -
Why is django debug toolbar causing a 'ValueError at ... Another profiling tool is already active' error when Htmx ajax fires?
I had django-debug-toolbar working fine in my application until I added htmx. Now I'm getting Another profiling tool is already active error. The page loads then htmx fires on load to add more content. Below is the offending line <div id="group-list" hx-get="{% url "my-rental-property-groups" rental_property.id %}" hx-trigger="load"></div> If I change the change the hx-trigger attribute to hx-trigger="load delay:5s" to add a delay of 5 seconds, then the error goes away but that's not a solution. A smaller delay still throws the same error. If I add "SHOW_TOOLBAR_CALLBACK": lambda request: False, to DEBUG_TOOLBAR_CONFIG section below, the page renders fine but the Debug Toolbar is disabled DEBUG_TOOLBAR_CONFIG = { "SHOW_TOOLBAR_CALLBACK": lambda request: False, #THIS LINE DISABLES DEBUG TOOLBAR WIHOUT SETTING DEBUG TO FALSE "SHOW_TEMPLATE_CONTEXT": True, "ROOT_TAG_EXTRA_ATTRS": "hx-preserve", # https://django-debug-toolbar.readthedocs.io/en/latest/tips.html#working-with-htmx-and-turbo } I'm looking for a solution that will allow me to keep Htmx and Django Debug Toolbar working together. -
Docker-compose: Creating same container for different projects
I'm facing an issue with my Django projects that have a similar structure. Each project has a backend folder containing a docker-compose.yml and Dockerfile. The structure is as follows: project1/backend/docker-compose.yml project2.backend/docker-compose.yml The problem arises when I switch between projects and run docker-compose up. It seems that the container named backend is reusing services from the previous project instead of creating a new container. Here's an example of the docker-compose.yml for each project: Project 1: version: '3.9' services: redis: image: redis:latest ports: - "6379:6379" postgres: image: postgres:12 container_name: postgres environment: POSTGRES_PASSWORD: project_name POSTGRES_DB: project_name env_file: - .env ports: - "5432:5432" volumes: - postgres_data:/var/lib/postgresql/data/ celery: build: context: . dockerfile: Dockerfile command: celery -A project_name worker -l info volumes: - .:/opt/webapp depends_on: - redis - postgres celery-beat: build: context: . dockerfile: Dockerfile command: celery -A project_name beat -l info volumes: - .:/opt/webapp depends_on: - redis - postgres volumes: postgres_data: Project 2: version: "3.9" services: web: build: context: . args: SECRET_KEY: ${SECRET_KEY} env_file: .env volumes: - ./:/opt/webapp ports: - "8000:8000" # Added Command for hot reloading in dev server command: > sh -c "python3 manage.py runserver 0.0.0.0:8000" postgres: env_file: .env environment: POSTGRES_PASSWORD: project_name volumes: - postgres-data:/var/lib/postgresql/data ports: - "5432:5432" redis: env_file: .env ports: - … -
How to use Django AutocompleteFilter thtough 2 relations?
i have Django models hierarchy class Workspace(Model): title = CharField() class User(Model): workspace = ForeignKey(to=Workspace) class Chat(Model): user = ForeignKey(to=User) In Django admin at Chats page i want to filter them by workspace, but there are many workspaces, so i need select2 At Users page i use AutocompleteFilter (django-admin-autocomplete-filter package) But it do not work at Chats page. Questions: Is it possible to use AutocompleteFilter in this case? How? Are there any other solution to make Autocomplete dropdown filters? -
How to connect django 5.0.3 to SQL Server database
I have been trying to connect django with SQL server but there are errors occurring continuously no matter what I try. For example DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'xxxxx', 'USER': 'xxxx', 'PASSWORD': 'xxxx', 'HOST': 'xxxxx', 'PORT': '1433', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, }, } I get this error: File "C:\Users\Admin\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\models\sql\where.py", line 180, in as_sql raise FullResultSet django.core.exceptions.FullResultSet When I change Engine to "mssql" I get this error: django.core.exceptions.ImproperlyConfigured: 'mssql' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' -
DJANGO ImportError: cannot import name 'url' from 'django.conf.urls' version 5.0.3
I'm following this DJANGO Rest Framework tutorial: https://www.youtube.com/watch?v=eA4H3p95hbM&list=PLmDLs7JbXWNjr5vyJhfGu69sowgIUl8z5&index=4 After modifying in 'urls.py', then type "python manage.py migrate" I get this error: from django.conf.urls import url ImportError: cannot import name 'url' from 'django.conf.urls' (F:\Learning HTML and CSS\DJANGO_DAVE GRAYE.venv\Lib\site-packages\django\conf\urls_init_.py) urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) I have search solution for this error. But they are working on DJANGO version 4.0 above and my current version is 5.0. I try follow their solution but it seems not working in my case -
his error originates from a subprocess, and is likely not a problem with pip
pip install validate email Collecting validate Using cached validate-1.0.1.tar.gz (32 kB) Installing build dependencies ... done Getting requirements to build wheel ... error error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> [23 lines of output] Traceback (most recent call last): File "C:\Users\beras.virtualenvs\django-GatewayMonitoring-website-_fBZbT0M\Lib\site-packages\pip_vendor\pyproject_hooks_in_process_in_process.py", line 353, in main() File "C:\Users\beras.virtualenvs\django-GatewayMonitoring-website-_fBZbT0M\Lib\site-packages\pip_vendor\pyproject_hooks_in_process_in_process.py", line 335, in main json_out['return_val'] = hook(**hook_input['kwargs']) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\beras.virtualenvs\django-GatewayMonitoring-website-_fBZbT0M\Lib\site-packages\pip_vendor\pyproject_hooks_in_process_in_process.py", line 118, in get_requires_for_build_wheel return hook(config_settings) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\beras\AppData\Local\Temp\pip-build-env-g_ifnqns\overlay\Lib\site-packages\setuptools\build_meta.py", line 325, in get_requires_for_build_wheel return self._get_build_requires(config_settings, requirements=['wheel']) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\beras\AppData\Local\Temp\pip-build-env-g_ifnqns\overlay\Lib\site-packages\setuptools\build_meta.py", line 295, in _get_build_requires self.run_setup() File "C:\Users\beras\AppData\Local\Temp\pip-build-env-g_ifnqns\overlay\Lib\site-packages\setuptools\build_meta.py", line 487, in run_setup super().run_setup(setup_script=setup_script) File "C:\Users\beras\AppData\Local\Temp\pip-build-env-g_ifnqns\overlay\Lib\site-packages\setuptools\build_meta.py", line 311, in run_setup exec(code, locals()) File "", line 13, in File "C:\Users\beras\AppData\Local\Temp\pip-install-6bmuq9nw\validate_74389ea5db364065a48c1b8f2d9e1ca1\configobj.py", line 1632 except Exception, e: ^^^^^^^^^^^^ SyntaxError: multiple exception types must be parenthesized [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> See above for output. note: This error originates from a subprocess, and is likely not a problem with pip. I'm currently working in a django project, and tried to install "validate email". I'm unable to install it.