Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ubuntu is not serving Static files from Django project. Getting Permission issue
I have a django project deployed on Ubuntu 23.04 and using nginx and gunicorn to serve the website. Static setting is defined as follows: STATIC_DIR=os.path.join(BASE_DIR,'static') STATIC_URL = '/static/' if DEBUG: STATICFILES_DIRS = [ STATIC_DIR, ] else: STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' We have Debug = False in Production. Gunicorn service [Unit] Description=gunicorn daemon Requires=opinionsdeal.socket After=network.target [Service] User=panelviewpoint Group=www-data WorkingDirectory=/home/panelviewpoint/opinionsdealnew ExecStart=/home/panelviewpoint/opinionsdealnew/venv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/opinionsdeal.sock \ opinions_deal.wsgi:application [Install] WantedBy=multi-user.target nginx file server { server_name opinionsdeal.com www.opinionsdeal.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/panelviewpoint/opinionsdealnew; } location / { include proxy_params; proxy_pass http://unix:/run/opinionsdeal.sock; } } SSL lines have been removed from nginx file in this code only but it is already there in server. I am using Django 4.2 and python 3.11 We are seeing that website HTML pages are being served but static files like js, css and images are not being served. I have deployed similar projects in past on ubuntu 20 and worked well but this time it is not working. I have given permission for static folder to all users. Please suggest if there is any solution. -
Is it possible to have a conditional statement distinguish which model a Python variable is coming from? [duplicate]
In my Django view I have 3 models and I want to do a conditional based on where a variable is coming from. I have tried... if (type(variable)) is ModelA: do this... If I do... print(type(variable)) it prints out '<class 'app.models.ModelA'>' But the conditional never kicks in. I'm not sure what I am missing. -
Django logon SSO through Active Directory without any actions with DC server
We are moving from Java-GWT-Tomcat on Python-Django-Apache. We have Active Directory and SSO mechanism as getting users member groups info. It's made with Waffle and it's doesn't require any server-side Kerberos keytab or adding service account in AD. Is there any way to do this with Python-Django-Apache? -
How to migrate database django from postgresql to mysql
Please help me, yesterday I switched providers to deploy my django website, in the old provider I used postgresql as the database, but in the new provider only supports mysql, so inevitably I have to migrate my database to mysql. For the database settings in my django project I have adjusted as follows: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'achmadir_portfolio', 'USER': '**************', 'PASSWORD': ******************', 'HOST': 'localhost', 'PORT': '3306', } } I have previously backed up my database and I want to restore it in django on a new provider. But when I want to migrate in the terminal with : python manage.py migrate There is an error : django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'None) NOT NULL, `gambar` varchar(100) NOT NULL, `gambar2` varchar(100) NOT NULL,' at line 1") For information, I have included the code information in the models in the application that indicated the error which can be seen in the error information: from django.db import models from django.utils import timezone from django.utils.text import slugify # Create your models here. class Proyek(models.Model): ITEM_CHOICES = [ ('SQL', … -
Django : Using Onclick To Div With Scrolling ( Tab Menu )
I'm trying to create tab menu with scroll. My actual problem is, How to scroll to section by clicking the button? Smooth scroll to div id Is there a better way to do this? Thank you my code : html <section id="section_{{ html_component.title }}" class="card"> <div> <div> <h3>{{ html_component.title }}</h3> </div> </div> </section> <section id="section_{{ html_component.title }}" class="card"> <div> <div> <h3>{{ html_component.title }}</h3> </div> </div> </section> <nav class="menu__main"> <ul> {% for html_component in html_components %} <li> <a href="javascript:void(0);" onclick="ScrollTabMenu()"> <span>{{ html_component.title }}</span> </a> </li> {% endfor %} </ul> </nav> jquery function ScrollTabMenu (){ let TabMenu = $(`section_{{html_component.title}}`) }; Please tell me the best solution for jQuery or Javascript? -
how to correct the spacing of texts?
I made this blog but when I write a post in the write a new post page the spaces between the lines and all that is correct but when I post it and go to detail.html to see it it all just displays beneath each other with no space between the lines what should I do? if I need to post another page please let me know I appreciate your help new.html {% extends "base.html" %} {% load crispy_forms_tags %} {% block content %} <form method="post"> <style> textarea { resize: none; } </style> {% csrf_token %} <div style="margin-top: 15px"></div> <fieldset class="form-group"> <legend class="border-bottom mb-4">Create Post</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <div style="margin-top: 20px"></div> <button class="btn btn-outline-info" type="submit">Create</button> </div> </form> {% endblock %} detail.html {% extends "base.html" %} {% load static %} {% block content %} <html> <div style="margin-top: 20px"></div> <body class="text-center" style="line-height: 2;"> <article> <h1>{{post.title}}</h1> <p style="margin-top: 15px;">{{post.body}}</p> </article> </body> <div style="margin-top: 24px"></div> <a style="color: darkgray; font-size: 22px;"> <img src="{% static 'website/icons8-sparkles-25.png'%}"> Written by {{post.author}} <img src="{% static 'website/icons8-sparkles-25.png'%}"> </a> </html> {% endblock %} looks like this while writing looks like this when posted -
How can I add additional metadata into the django.server logs?
What I am trying to do is as given below, The current logs for the server requests look like the following. [29/Nov/2023 02:33:50] "GET /api/health/ HTTP/1.1" 200 31 The new format I need is as following. [29/Nov/2023 02:33:50] "GET /api/health/ HTTP/1.1" 200 31 user-id:<user_id> I tried to add a logs filter. "django.server": { "()": "django.utils.log.ServerFormatter", "format": "[%(asctime)s] %(levelname)s %(module)s %(message)s user_id:%(user_id)s ", } The following is my filter. class UserIdFilter(logging.Filter): def filter(self, record): user_id = None if hasattr(record, "request"): try: user_id = record.request.user.id except Exception as exp: user_id = "anon" if not user_id: user_id = "unknown" record.user_id = user_id return True The problem is the record object above is a socket.socket object and does not have any request http payload metadata. What could I do differently to find and append the request user_id to the logs? -
Django and staticfiles
I have a problem with Django static files. Let's assume, that the Django is configured to be server at www.example.com/app. When my configuration is: STATIC_URL = "/static/" MEDIA_URL = "/media/" STATIC_ROOT = "/home/hostxxx/domains/webpage.com/DjangoApp/static" MEDIA_ROOT = "/home/hostxxx/domains/webpage.com/DjangoApp/media" Then Django looks for: https://example.com/static/styles/style.css and it doesn't exist: GET https://example.com/static/styles/style.css net::ERR_ABORTED 404 (Not Found) but the file exists here: https://example.com/app/static/styles/style.css But when I change the static url: STATIC_URL = "/app/static/" Then it looks for a good url: https://example.com/app/static/styles/style.css but now the staticfile is available here: https://example.com/app/app/static/styles/style.css Update: urls.py: from django.contrib import admin from django.urls import path from mainapp import views urlpatterns = [ path("admin/", admin.site.urls), path("", views.lists, name="lists"), # MAIN VIEW ] but tried also this as urls.py: from django.contrib import admin from django.urls import path from django.contrib.staticfiles.urls import staticfiles_urlpatterns from mainapp import views urlpatterns = [ path("admin/", admin.site.urls), path("", views.lists, name="lists"), ] urlpatterns += staticfiles_urlpatterns() and base.html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>AAA</title> <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" /> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css" /> <link rel="stylesheet" href="{% static 'styles/style.css' %}"> # HERE ... The hosting use passenger_wsgi.py, which is: import imp import os import sys sys.path.insert(0, os.path.dirname(__file__)) wsgi = imp.load_source("wsgi", "app/wsgi.py") application = wsgi.application django-admin --version: 5.0 python --version: … -
Django Migration Error with PostGIS: 'double free or corruption (out) Aborted (core dumped)
I am developing a web application using Django and encountering a critical issue during database migration with PostGIS. While migrations work seamlessly with the SpatiaLite engine, switching to the PostGIS engine leads to a crash. The error message I receive is: "double free or corruption (out) Aborted (core dumped)". This issue arises specifically when I attempt to make migrations with the PostGIS engine. My Django project settings for the database are as follows: DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'geodesia_interoperable', 'USER': 'depiction', 'PASSWORD': '************', 'HOST': 'localhost', 'PORT': '5432', } } I have verified that PostgreSQL and PostGIS are correctly installed and configured, and the database credentials are accurate. The application runs as expected with SpatiaLite but fails when switched to PostGIS. Has anyone encountered a similar issue, or does anyone have insights into what might be causing this error with PostGIS in Django? Any suggestions for troubleshooting or resolving this problem would be greatly appreciated. -
React: 'map' function
I'm fetching a list of objects. Using map function should display a list but there wasn't. I checked if it was saved to 'useState' via console.log(posts), and yes there was a list of objects. My only problem is I cant display it to the browser. Also, I already attached the necessary scripts for 'react', 'reactDOM', and 'babel'. {% extends "network/layout.html" %} {% block body %} <div id="index"></div> <script type="text/babel"> const AllPosts = () => { const [posts, setPosts] = React.useState([]); React.useEffect(() => { fetch("/allposts") .then((response) => response.json()) .then((data) => { setPosts(data.posts); }) .catch((error) => { console.error(error); }); }, []); return ( <ul> {posts && posts.map((post, index) => { <li key={index}>{`Try ${index}`}</li>; })} </ul> ); }; const Index = () => { return <AllPosts />; }; const container = document.getElementById("index"); const root = ReactDOM.createRoot(container); root.render(<Index />); </script> {% endblock %} I wanted to return each object on the list in an li tag, however, there was no data when I inspected it on the browser. -
Django 5.0: How GeneratedField actually works?
I've read the Django documentation about the new models.GeneratedField, but I don't quite understand how it works inside a database. Can someone explain this? -
CannotPullContainerError: pull image manifest has been retried failed to resolve ref xxxxx.dkr.ecr.us-east-1.amazonaws.com/xxx-proxy:latest: not found
After reading through docs I still cant seem to resolve this myself. The proxy image does have the tag of "dev" which ive tried to add and was thrown a seperate error saying failed to normalize image. Currently using Fargate v1.4.0. I have a IAM CI user with given permissions for building/reading etc. variables.tf variable "ecr_image_proxy" { description = "ECR Image for API" default = "xxxxxx.dkr.ecr.us-east-1.amazonaws.com/xxxxxxxx-proxy:latest" } ecs.tf resource "aws_iam_role_policy_attachment" "task_execution_role" { role = aws_iam_role.task_execution_role.name policy_arn = aws_iam_policy.task_execution_role_policy.arn } resource "aws_iam_role" "app_iam_role" { name = "${local.prefix}-api-task" assume_role_policy = file("./templates/ecs/assume-role- policy.json") tags = local.common_tags } data "template_file" "api_container_definitions" { template = file("templates/ecs/container- definitions.json.tpl") vars = { app_image = var.ecr_image_api proxy_image = var.ecr_image_proxy django_secret_key = var.django_secret_key db_host = aws_db_instance.main.address db_name = aws_db_instance.main.db_name db_user = aws_db_instance.main.username db_pass = aws_db_instance.main.password log_group_name = aws_cloudwatch_log_group.ecs_task_logs.name log_group_region = data.aws_region.current.name allowed_hosts = "*" } } resource "aws_ecs_task_definition" "api" { family = "${local.prefix}-api" container_definitions = data.template_file.api_container_definitions.rendered requires_compatibilities = ["FARGATE"] network_mode = "awsvpc" cpu = 256 memory = 512 execution_role_arn = aws_iam_role.task_execution_role.arn task_role_arn = aws_iam_role.app_iam_role.arn volume { name = "static" } tags = local.common_tags } resource "aws_ecs_service" "api" { name = "${local.prefix}-api" cluster = aws_ecs_cluster.main.name task_definition = aws_ecs_task_definition.api.family desired_count = 1 launch_type = "FARGATE" platform_version = "1.4.0" network_configuration { subnets … -
customize django admin panel login view
I Want to do a little job when an admin wants to log into the admin panel. and that's it: I have a gateway service and I want from that gateway to handle authenticating of my users and just give me a token and then I handle them with the help of that token. now I'm confused how can I add my preferred logic alongside with all the default logic of handling authentication and logging admins into admin panel of django. I tried to override the default method, or even copy & paste that logic all by hand :/ thanks for any help or recom.. :) -
Django floatformat: no unnecessary zeros
Django's floatformat filter has a few options for formatting decimals. However, none of them work for what I consider the "standard" way to represent decimals in non-programming fields, like math or science. Specifically, I'd like decimals to be displayed with "as many decimal places as needed", up to a defined limit. Here are some examples with a limit of 3: The decimal What I want floatformat floatformat:3 floatformat:"-3" 15.000000 15 15 ✅ 15.000 ❌ 15 ✅ 15.666667 15.667 15.7 ❌ 15.667 ✅ 15.667 ✅ 15.550000 15.55 15.6 ❌ 15.550 ❌ 15.550 ❌ 15.500000 15.5 15.5 ✅ 15.500 ❌ 15.500 ❌ Tests passed: 2/4 1/4 2/4 The closest filter for my goal is probably {{ thing | floatformat:"-3" }}, and that's what I'm using right now. All I would like is to remove the "trailing zeros" from this filter's output. Thanks a lot! -
Cant import views django
I Tried importing app views into my url patterns but i get this error, using newest django version and python 3.11 File "C:\Users\IK959\mysite\mysite\urls.py", line 18, in <module> from chatapp.views import chat_view ImportError: cannot import name 'chat_view' from 'chatapp.views' (C:\Users\IK959\mysite\chatapp\views.py) this is my directory enter image description here and this is my code for my url pattern and my view urlpattern: from django.contrib import admin from django.urls import include, path from chatapp.views import chat_view urlpatterns = [ path("polls/", include("polls.urls")), path("admin/", admin.site.urls), path('chat/', chat_view, name='chat'), ] chatapp view: from django.shortcuts import render def chat_view(request): return render(request, 'chatapp/chat.html') Ive tried the index but i do not know how to do it correctly -
Django 5.0 how to serialize class-based sessions without django.contrib.sessions.serializers.PickleSerializer
I saw Django 5.0 was released today and I am messing around with it, but I see that the PickleSerializer was removed. What is the preferred way of serializing class-based session data now? I see it states use JSON but that breaks my code as I store actual objects in the session for easy reference in some instances (so I get messages that Model object is not JSON serializable), is there an easier, yet still secure way to pickle sessions in Django? -- I store objects inside of sessions occasionally and it works really well for db related access and things of the sort as I don't need to recall the DB. In my settings I was using: SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer' You can see it was depreciated in 4.2 and removed in 5.0 here: https://github.com/django/django/blob/stable/4.2.x/django/contrib/sessions/serializers.py As a note, I am trying to figure out if I should alter my code to not store objects via pickle in my session, or if it really matters given I validate and grab data based on my defined objects, not specifically user-defined input -
ERROR on gunicorn: Can't connect to ('156.220.159.63', 8000)
I want to link NGINX with the Django project, so made conf/gunicorn_conf.py file, which includes: command = '/home/omnia/griphr-backend/.venv/bin/gunicorn' pythonpath = '/home/omnia/griphr-backend' bind = '156.220.159.63:8000' workers = 3 I ran it, but got this error: why raise this error? I am sure that the IP is correct -
Trouble Parsing JSON Data in Python [closed]
I'm currently working on a Python project where I'm receiving JSON data from an API, but I'm facing difficulties parsing it correctly. The JSON data looks like this: "name": "John Doe", "age": 30, "email": "johndoe@example.com", "address": { "street": "123 Main St", "city": "Anytown", "zip": "12345', "skills": ["Python", "JavaScript", "SQL"] I'm trying to extract specific information from this JSON object, such as the person's name, age, and skills. However, I'm not sure how to correctly parse this JSON in Python to access this data. Could someone provide an example of how I can extract this information from the JSON object and store it into variables or access it directly? -
"MultipleObjectsReturned or ObjectDoesNotExist error when accessing 'google' provider in Django-allauth"
I'm encountering an issue when trying to access the 'google' provider in Django-allauth. I'm getting either a MultipleObjectsReturned or ObjectDoesNotExist exception. I have followed the documentation and tried various troubleshooting steps, but the problem persists. Here is the code snippet from my views.py file: from allauth.socialaccount.models import SocialApp from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist def home(request): try: google_provider = SocialApp.objects.get(provider='google') except MultipleObjectsReturned: print("Multiple 'google' providers found:") for provider in SocialApp.objects.filter(provider='google'): print(provider.client_id) raise except ObjectDoesNotExist: print("No 'google' provider found.") raise return render(request, 'home.html', {'google_provider': google_provider}) I have also imported the necessary modules SocialApp and MultipleObjectsReturned/ObjectDoesNotExist from allauth.socialaccount.models and django.core.exceptions respectively. I have checked my database, and there is only one entry for the 'google' provider in the SocialApp table. The client_id is correctly set for this provider. Despite taking these steps, I am still encountering the mentioned errors. I have made sure to restart my Django server after any code or database changes. -
Django : can't return redirect in a sub function exception. The first function continues
I've got a function a() that calls other functions b() , c() and d() this way (I schematize): a() def a(request): try: b(request) except Exception: messages.error(request, 'error') try: c(request) except Exception: messages.error(request, 'error') try: d(request) except Exception: messages.error(request, 'error') return redirect('namespace:url_name') b() def b(request): try: do_something() messages.success(request, 'I did') except Exception: messages.error(request, 'Couldn\'t do the thing') return redirect('namespace:url_name') But if an exception triggers in b() , its redirection doesn't work and c() and d() are still executed in a(). Did I miss something in my redirect or exception handling comprehension ? Because even if I set a redirect in all a functions' Exceptions, the behavior doesn't change. -
Issue with Django Migration - "Table already exists
I'm encountering a problem while trying to run migrations in my Django project. When I run python manage.py migrate, I'm getting the following error: django.db.utils.OperationalError: (1050, "Table 'myapp_mymodel' already exists") This error seems to be related to a table already existing in the database, but I haven't manually created it, and it's not in my migration files. I've tried the following steps: Checked migration files for any duplicates or errors. Deleted the database and recreated it. Verified that there are no stray migration files in the app. -
"How can I implement user authentication and authorization in a modern web application using [specific technology or framework]?" [closed]
How do I implement secure user authentication and authorization in a web application using the Django framework? Seeking best practices and code examples to ensure robust user management and access control." I implemented Django user authentication and authorization using official documentation. Expected users to register, log in, and access authorized content. Encountered an issue where authentication succeeded, but authorization failed for specific views." -
Reverse for 'create_submission_form' with keyword arguments '{'docstash_key': ''}' not found
- this is the error: NoReverseMatch at /dashboard/ Reverse for 'create_submission_form' with keyword arguments '{'docstash_key': ''}' not found. 1 pattern(s) tried: ['core/submission/new/(?P<docstash_key>[^/]+)/\\Z'] this is the line in html that is causing the error: <a class="dropdown-item" href="{% url 'core:create_submission_form' docstash_key=docstash.key %}"> this is the url path: path('new/<str:docstash_key>/', views.create_submission_form, name='create_submission_form'), -this is the view function: @with_docstash() def create_submission_form(request): if request.method == 'POST' and 'initial' in request.docstash: del request.docstash['initial'] # XXX: docstash will be saved further down form = SubmissionFormForm(request.POST or request.docstash.POST, initial=request.docstash.get('initial', {}).get('submission_form')) formsets = get_submission_formsets(request.POST or request.docstash.POST, initial=request.docstash.get('initial')) documents = Document.objects.filter(pk__in=request.docstash.get('document_pks', [])) protocol_uploaded = documents.filter(doctype__identifier='protocol').exists() if request.method == 'GET' and not request.docstash.POST and \ not 'initial' in request.docstash: protocol_uploaded = True # don't show error on completely new # submission # neither docstash nor POST data: this is a completely new submission # => prepopulate submitter_* fields with the presenters data profile = request.user.profile form.initial.update({ 'submitter_contact_first_name': request.user.first_name, 'submitter_contact_last_name': request.user.last_name, 'submitter_email': request.user.email, 'submitter_contact_gender': profile.gender, 'submitter_contact_title': profile.title, 'submitter_organisation': profile.organisation, 'submitter_jobtitle': profile.jobtitle, }) if 'notification_type_id' in request.docstash: notification_type = NotificationType.objects.get( id=request.docstash['notification_type_id']) else: notification_type = None if 'submission_id' in request.docstash: submission = Submission.objects.get( id=request.docstash['submission_id']) else: submission = None valid = False if request.method == 'POST': submit = request.POST.get('submit', False) save = request.POST.get('save', False) autosave = … -
Django capture traces of all invoked function Open Telemetry
I am a newbie to Open Telemetry and trying to see how traces are captured for a Django app. I am assuming that OTel should be able to provide traces of all invoked functions for a particular Django Request. E.g.I have a very basic Django app with a views.py as def log_console(): print("Print in terminal") def show_date(): now = datetime.now() log_console() return HTMLResponse() The url is configured to serve show_date My expectation js that when I configure manage.py with DjangoInstrumentor().instrument() In the console I should be able to see reference to the function log_console as it is invoked when serving the show_date But cant see any reference to log_console, not sure if this is a valid use case for Tracing in Open Telemetry -
Django's Very slow initial execution of select query on remote Oracle 11 database when table contain big blobs
I actually understand what is causing the problem but can't figure out a solution that works with Django. suppose you are trying to read 10,000 records from oracle database over network, normally that would result in 10,000 network connections being open and closed which causes bad performance. Oracle's answer to that is to send say 1000 records at once per connection, that significantly improve the speed. However in my case, each row contains blobs that are 1-2MBs, so trying to prefetch 1000 records means nothing happens until I've downloaded (and kept in memory) 1GB-2GB worth of data. oracle's sqlplus provides option to control that, either using the fast parameter or issuing set rowprefetch 10 but I can't find solution that works with Django. I only want to prefetch 10 records or so