Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting page not found error on my website build in Django & React in netlify after deployment
Page Not Found Looks like you've followed a broken link or entered a URL that doesn't exist on this site. Back to our site If this is your site, and you weren't expecting a 404 for this path, please visit Netlify's "page not found" support guide for troubleshooting tips. and also did alowed host to * but still i am not able to host please help This is my github repo. this is the error i am getting i have added netlify.toml file too in my package.json directory please refer to my repo -
Django_ CreateView class showing class availability
I have a Gym Project in django, with booking_create (CreateView) to create bookings for a gym class. I am using a Model and Form, with user and class types. The HTML template has a Form for class booking. I want to make this Form unavailable when the class is full booked, showing instead a warning message. My thoughts: I should have a booking count for created bookings (e.g., booking_count), rest this value to the class capacity and save this in a variable (like, av_places= class_capacity-booking_count) and if av_places is greater than zero, show the Form for registration, otherwise show a warning message. Not sure how to add this functionality to the class view Below are the class model, view and template. models.py: class Class_Book (models.Model): user= models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) class = models.ForeignKey(Class, on_delete=models.CASCADE,default= '') def __str__(self): return f'{self.class}' views.py class booking_create (LoginRequiredMixin,CreateView): form_class= Booking_Form template_name= ‘booking_create.html' success_url=reverse_lazy('home') template: <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button class="btn btn-success" type="submit">SAVE</button> </form> -
Django:: ImproperlyConfigured: Pooling doesn't support persistent connections
I've recently upgraded to Django 5.1 and configured the database pooling option with the following settings: DATABASES["default"]["OPTIONS"] = { "pool": {"min_size": 2, "max_size": 4, "timeout": 10} } DATABASES["default"]["CONN_MAX_AGE"] = None However, I encountered the following error: ImproperlyConfigured: Pooling doesn't support persistent connections. I understand that removing CONN_MAX_AGE = None will resolve this issue, but I would like to gain a deeper understanding of this limitation. Specifically, is the restriction on using persistent connections with pooling a constraint unique to Django's implementation, or does it extend to PostgreSQL (or other databases) in general? Additionally, what are the underlying reasons for this incompatibility? -
Guidance Needed for Building a Django Project with Custom User Management and JWT Authentication
Hi StackOverflow Community, I'm working on a Django project with specific requirements and technical constraints, and I'm looking for guidance on how to approach it. Here are the details: Business Requirements: Login Users should be able to log in, and the system should handle successful and failed logins, account lockouts, and password recovery. Logout with Session Store Implement secure logout, handle session timeouts, and ensure session persistence across browser tabs. User Management Admins should be able to create, edit, deactivate user accounts, and view user activity logs. Roles and Permissions Admins should manage roles and permissions, assign roles to users, and modify role permissions. Technical Specifications: APIs: Must follow RESTful standards. Authentication: JWT is the preferred token type. Database: MongoDB. ORM: Official Django ORM should not be used. Model Management: Prefer using Pydantic. Coding Standards: Follow PEP8 for Python. APIs Framework: Use django-rest-framework. Class-Based Design: The implementation should be class-based and object-oriented (no functional programming). Current Knowledge and Setup: I am familiar with Django and REST frameworks but need guidance on integrating MongoDB without using Django ORM, managing models with Pydantic, and implementing JWT authentication. Questions: Setup Guidance: What are the best practices for integrating Django with MongoDB using Djongo … -
User Discord Avatar Not Displaying in Django Template
Django Python OAuth Discord getting an avatar from the Discord API, please help me how to do this. On the index.html page, the user's avatar is not displaying in the <div class="auth"> block. I have tried several methods, but none worked. I can't find information on how to properly load the user's avatar. Here is the relevant code: index.html: <div class="auth"> {% if user.is_authenticated %} <div class="user-info"> <img style="z-index: 9099;" src="{{ user.avatar }}" alt="User Avatar"> <p>{{ user.avatar }}</p> <p>{{ user.username }}</p> <a href="{% url 'account_logout' %}" class="logout-button">Logout</a> </div> {% else %} <div class="auth-buttons"> <a href="{% url 'account_login' %}" class="login-button">Login</a> <a href="{% url 'account_signup' %}" class="register-button">Register</a> <a href="{% provider_login_url 'discord' method='GET' process='connect' %}" class="discord-button">Login with Discord</a> </div> {% endif %} </div> models.py: from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): discord_user_id = models.CharField(max_length=50, blank=True, null=True) discord_avatar_hash = models.CharField(max_length=100, blank=True, null=True) def get_discord_avatar_url(self): if self.discord_user_id and self.discord_avatar_hash: return f"https://cdn.discordapp.com/avatars/{self.discord_user_id}/{self.discord_avatar_hash}.png" return None views.py: def index(request): return render(request, "html/index.html") urls.py: from django.contrib import admin from django.urls import path, include from meow_app import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), path('about/', views.about, name='about'), path('terms/', views.terms, name='terms'), path('politika/', views.politika, name='politika'), path('events/', views.events, name='events'), path('accounts/', include('allauth.urls')), path('logout/', TemplateView.as_view(template_name='logout.html'), name='logout'), path('', include('meow_app.urls')), ] Django … -
Managing Multiple OAuth Providers in Django/DRF
Let's say I have two OAuth providers, Google and GitHub with which user can create an account in my Django application. I wrote a custom user model and a custom model for storing OAuth details (provider and user ID from provider etc.). Let's say the user logs-in with GitHub first and creates an account. He logs out, signs-up again, but this time with Google. Now what happens? How can I know that the user already has an account linked with GitHub? I cannot check the email because their email can be different for different platforms. I cannot use the ID of the user from OAuth provider too. Please do not ask me to use libraries, I'm willing to learn how to implement it on my own. -
How to delete Goods in Qoo10 by API in Django
I am using Qoo10.jp api to publish the goods on Qoo10 store. It working well but when I trying to delete a good it does not work. I tried likes this in Django. params = { 'key': user.qoo10_sak, 'v': '1.0', 'returnType': 'json', 'method': 'ItemsBasic.DeleteGoods', 'ItemCode': m_product.code, } response = requests.get('https://api.qoo10.jp/GMKT.INC.Front.QAPIService/ebayjapan.qapi', params) print(response.status_code) When I print the response status_code it 200 but the response body is Can't find method Info Delete How to solve this issue. -
Custom Widget for Search Bar
I wanted to define a custom widget SearchBar, which when associated with a CharField, would automatically render a text input box for search, followed by a search button. I created a template html and put it at a custom location. I tried to create a new widget by inheriting from django.forms.widgets.Input, but when I give template_name=, it tries to locate the path in django/forms/templates only, not my custom location myapp/forms/templates. It looks like this path is baked into django.template.backends.django.DjangoTemplates. Is there a simpler way than inheriting from DjangoTemplates then adding template paths to achieve what I want? BTW, I use Bootstrap5, and so also use django-bootstrap5, so I suppose I need to write a renderer for this too. Would I be better off manually rendering the field and button in every form by hand rather than define a custom widget? -
Send notifications with pyfcm to multiple tokens
I'm using the latest version of pyfcm and I did saw a function called async_notify_multiple to send multiple tokens. But it is not working. How to send multiple notifications. Thanks -
Jinja Template Render
i have a jinga template like below: <span>Holiday Quote Includes</span> {% set rendered_bits = [] %} <div class="flex fontWeight400 tour_includes-items"> {% for bit in bits %} {% if bit == 'hotel' and 'hotel' not in rendered_bits %} <div class="flex fontWeight400 tour_includes-item"> <img src="https://Hotel.svg" alt=""> Hotel </div> {% set rendered_bits = rendered_bits + ['hotel'] %} {% elif (bit == 'drive' or bit =='transfer' or bit == 'intercity' or bit == 'multicity' or bit == 'rental') and 'transport' not in rendered_bits %} <div class="flex fontWeight400 tour_includes-item"> <img src="https://Transport.svg" alt=""> Transport </div> {% set rendered_bits = rendered_bits + ['transport'] %} {% elif (bit == 'flight') %} <div class="flex fontWeight400 tour_includes-item"> <img src="https://Airplane_VW.svg" alt=""> Flight </div> {% set rendered_bits = rendered_bits + ['transport'] %} {% elif bit == 'paid_activity' and 'sightseeing' not in rendered_bits %} <div class="flex fontWeight400 tour_includes-item"> <img src="https://Sightseeing.svg" alt=""> Sightseeing </div> {% set rendered_bits = rendered_bits + ['sightseeing'] %} {% endif %} {% endfor %} </div> </div> here i am rendering this template with: bits = {'flight', 'hotel', 'intercity', 'paid_activity', 'transfer'}} the Problem here is for bits 'intercity' and 'transfer' the corresponding div should only be rendered once. But its getting rendered twice. below is the rendered data: <div class="row text-center" … -
CORS Error with Angular 13 Frontend and Django Backend [duplicate]
I’m currently working on a project using Angular 13 for the frontend and Django for the backend. I’ve developed a login page that fetches a background image via a GET API call from the Django backend. However, I’m encountering a CORS (Cross-Origin Resource Sharing) error when making the request. Here’s a summary of the issue: Frontend: Angular 13 application Backend: Django application Feature: Login page fetching background image through a GET request Issue: I’ve attempted to resolve the CORS error by adding the Access-Control-Allow-Origin header in the backend response, but the error persists. I'm unsure whether this issue should be resolved on the frontend side or the backend side. Steps Taken: Added 'Access-Control-Allow-Origin' header in request header. installed cors extension in browser. Code and Images: I have attached relevant code snippets and images for better understanding. login.service.ts [![enter image description here][1]][1] import { Injectable } from '@angular/core'; import {HttpClient, HttpHeaders} from '@angular/common/http'; import { environment } from '../environments/environment'; @Injectable({ providedIn: 'root' }) export class LoginService { rootURL:any; constructor(public http:HttpClient) { this.rootURL = environment.apiUrl; } getBackGroundImage(){ let header = { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' } return this.http.get(`${this.rootURL}/login/cors/img/backgrounds/login/28.jpg?1907c5373b7`,{headers: header}); } } login.component.ts import { Component, OnInit } from '@angular/core'; import {FormControl, FormGroup, … -
NoSuchKey error when deleting django-avatar file saved on DigitalOcean Spaces
I recently upgraded and older Django project to Django 4.2 using the DigitalOcean App Platform. Everything seemed to go fairly smoothly except when trying to delete items managed by the django-avatar package, where the avatar images are stored on DO Spaces (S3 object storage). Saving images using django-storages with boto3 to handle the s3 objects still works fine, however, when deleting items through the admin ui it throws the following: NoSuchKey at /admin/avatar/avatar/37/delete/ An error occurred (NoSuchKey) when calling the ListObjects operation: None Request Method: POST Request URL: http://localhost/admin/avatar/avatar/37/delete/ Django Version: 4.2.9 Exception Type: NoSuchKey Exception Value: An error occurred (NoSuchKey) when calling the ListObjects operation: None Exception Location: /usr/local/lib/python3.10/site-packages/botocore/client.py, line 964, in _make_api_call Raised during: django.contrib.admin.options.delete_view Python Executable: /usr/local/bin/python Python Version: 3.10.14 Python Path: ['/app', '/app', '/usr/local/bin', '/usr/local/lib/python310.zip', '/usr/local/lib/python3.10', '/usr/local/lib/python3.10/lib-dynload', '/usr/local/lib/python3.10/site-packages'] After reviewing every SO issue that could be related to this for django-avatar (8.0), boto3 (1.34), and DO Spaces issues, I haven't come up with anything that points me in the right direction. I have verified the key exists and it also has no issues displaying the avatar images. This error appears to be coming from botocore, but attempting to delete other images and files (media or static … -
Django will not connect to mysql container on port 3307 with 3307:3306 mapped in docker compose file
docker-compose.yaml services: db: image: mysql:9.0.1 container_name: db_mysql_container environment: MYSQL_DATABASE: backend MYSQL_USER: asdf MYSQL_PASSWORD: asdf MYSQL_ROOT_PASSWORD: asdf ports: - '3307:3306' api: build: . container_name: django_container command: bash -c "pip install -q -r requirements.txt && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - .:/app ports: - '8000:8000' depends_on: - db django settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': "backend", 'USER': "asdf", 'PASSWORD': "asdf", 'HOST': "db", 'PORT': "3307", } } The rest of my django settings file is what the default is. The whole django project is just what you start out with from the django-admin startproject command, plus the mysqlclient dependency. Here is my Dockerfile, nothing special going on: # Use an official Python runtime as a parent image FROM python:3.12 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set the working directory WORKDIR /app # Install dependencies COPY requirements.txt /app/ # Copy the project code into the container COPY . /app/ requirements.txt: asgiref==3.8.1 Django==5.1 mysqlclient==2.2.4 sqlparse==0.5.1 When I bring up the db, wait, and then bring up the api, I get this: django.db.utils.OperationalError: (2002, "Can't connect to server on 'db' (115)") If I change my docker-compose.yaml to this: services: db: image: mysql:9.0.1 container_name: db_mysql_container … -
Django on CapRover Creates Local Directory Instead of Uploading Media to S3
I'm deploying a Django application using CapRover, and I'm running into an issue with django-storages s3 bucket. When I run the app locally, everything works fine, and media files are uploaded to my S3 bucket as expected. However, when I deploy the app to CapRover, Django creates a local directory named https:/bucketname.s3.amazonaws.com/media/ and stores the uploaded media files there instead of uploading them to S3. Here's my settings.py configuration: AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID', '') AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY', '') AWS_STORAGE_BUCKET_NAME = os.getenv('AWS_STORAGE_BUCKET_NAME', '') AWS_S3_REGION_NAME = os.getenv('AWS_S3_REGION_NAME', '') AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_DEFAULT_ACL = None AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } STATICFILES_STORAGE = 'project.storages.StaticStorage' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/static/' DEFAULT_FILE_STORAGE = 'project.storages.MediaStorage' MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/media/' MEDIA_ROOT = MEDIA_URL Any help is appreciated! -
Nginx server doesn't load static css files
I'm trying to deploy my django site to ubuntu server nginx by following this tutorial (https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu). Deployment works, but css not working. I figured it's something with collectstatic but not sure. Funny enough css worked properly for 0.0.0.0:8000 port. This is from settings.py STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] I noticed in tutorial that they don't have STATICFILES_DIRS... and... STATIC_URL and STATIC_ROOT are same 'static'. Could this be an issue...? also, tried editing path to static with sudo nano /etc/nginx/sites-available/django_project server { listen 80; server_name xxx.xx.xx.xxx; #my ip, just hide it for purpose of question location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/muser/django_project/static/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } Any idea what I did wrong? Thanks in advance! -
Collectstatic won't upload to s3, but boto3 scripting with .env credentials works
I've been trying this for about 24 hours now non-stop. Here's my settings.py: import os from dotenv import load_dotenv #import django-storages #import storages.backends.s3boto3 load_dotenv() DEBUG = False SECRET_KEY = os.getenv('SECRET_KEY') # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Static settings for S3 STATICFILES_STORAGE = storages.backends.s3boto3.S3Boto3Storage DEFAULT_FILE_STORAGE = storages.backends.s3boto3.S3Boto3Storage # These ensure that files are loaded to S3, make sure these values are in place: AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.getenv('AWS_STORAGE_BUCKET_NAME') AWS_S3_REGION_NAME = os.getenv('AWS_S3_REGION_NAME') # AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' STATIC_URL = f'https://{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com/static/' MEDIA_URL = f'https://{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com/media/' #STATICFILES_DIRS = [ # os.path.join(BASE_DIR, 'static'), # Assuming your static files are in a 'static' folder at the root of your project #] # Add a proper static root in case of local fallback STATIC_ROOT = os.path.join(BASE_DIR, 'static') # AWS-specific options AWS_S3_FILE_OVERWRITE = True AWS_DEFAULT_ACL = None AWS_S3_SIGNATURE_VERSION = 's3v4' AWS_QUERYSTRING_AUTH = False # Optional, useful if you want files to be public #print(f"AWS_ACCESS_KEY_ID: {AWS_ACCESS_KEY_ID}") #print(f"AWS_STORAGE_BUCKET_NAME: {AWS_STORAGE_BUCKET_NAME}") # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! ALLOWED_HOSTS = ['*'] INTERNAL_IPS = ['127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp.apps.myappAppConfig', … -
Django - Browser doesnt save cookies unless CSRF_COOKIE_DOMAIN is set
I have been trying to get CORS/CSRF working on my local and I found this weird issue that unless I set CSRF_COOKIE_DOMAIN to localhost as per this answer and I have no idea why its working. Reading up on it on MDN and MDN basically states that the current document url will be used if not set explicitly. Whats the correct reason for not saving cookies unless cookie domain is specified? for reference: my frontend url is http://localhost:5173 and I tried combinations of 127.0.0.1:5173 to get it working but it didnt without it. Here are my settings for Django base.py SESSION_COOKIE_HTTPONLY = True CSRF_COOKIE_HTTPONLY = False CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_SECURE = True X_FRAME_OPTIONS = "DENY" and local.py for local dev CSRF_TRUSTED_ORIGINS = ["http://localhost:5173", "http://127.0.0.1"] CSRF_COOKIE_DOMAIN = "127.0.0.1:5173" # CSRF_COOKIE_SAMESITE = "None" # SESSION_COOKIE_SAMESITE = "None" CSRF_COOKIE_SECURE = True # django-cors-headers CORS_ALLOWED_ORIGINS = [ "http://*.localhost:5173", "http://*.127.0.0.1:5173", "http://localhost:5173", "http://127.0.0.1:5173", ] CSRF_COOKIE_DOMAIN = "localhost" -
How to Perform a Reverse Join in Django ORM? Exactly like select_related but in reverse
Example models: class Order(models.Model): order_number = models.CharField(max_length=20) customer = models.CharField(max_length=100) class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) product = models.CharField(max_length=100) quantity = models.IntegerField() class Meta: unique_together = ('order', 'product') There is a one-to-many relationship between Order and OrderItem, but the unique_together constraint on ('order', 'product') ensures that for each order, there can only be one item per product. I want to fetch all orders for a specific customer that contain a specific product (say 'Laptop'), along with that particular OrderItem. In SQL, this would look like: SELECT * FROM order JOIN orderitem ON order.id = orderitem.order_id AND orderitem.product = 'Laptop' WHERE order.customer = 'John Doe'; In Django ORM, prefetch_related does this in two queries, but that’s inefficient because of the large result set and filtering. I want to know how to do this in one query using select_related or a similar method to apply the filter in the JOIN itself. How can I achieve this? the above models are for simplified demo but the actual use case I'm talking about involves millions of rows that's why it's strictly necessary to be a one query with join, and I'm so confused as to how I'm unable to do such a simple join … -
ADD to CART in DJANGO doesn't work in ecommerce website
I am following a tutorial of an ecommerce website in django and python. I have a problem with add to cart option. My code is the same as in a tutorial but it doesn't work. This is a github from a tutorial: [https://github.com/flatplanet/Django-Ecommerce] And I got this error: NoReverseMatch at /product/1 Reverse for 'cart_add' not found. 'cart_add' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/product/1 Django Version: 5.1 Exception Type: NoReverseMatch Exception Value: Reverse for 'cart_add' not found. 'cart_add' is not a valid view function or pattern name. Exception Location: C:\Users\Agata\PycharmProjects\ecom_pilates_shop\venv\DJANGO\Lib\site-packages\django\urls\resolvers.py, line 831, in _reverse_with_prefix Raised during: store.views.product Python Version: 3.11.2 I have tried to do some changes with chat gpt but nothing helps... This is my code: views: import json from django.shortcuts import render, get_object_or_404 from .cart import Cart # from store.models import Product # from django.apps import apps from django.http import JsonResponse from django.contrib import messages from ..store.models import Product # model = apps.get_model('store', 'Product') def cart_summary(request): # Get the cart cart = Cart(request) cart_products = cart.get_prods quantities = cart.get_quants totals = cart.cart_total() return render(request, "cart_summary.html", {"cart_products": cart_products, "quantities": quantities, "totals": totals}) def cart_add(request): # Get the cart cart = Cart(request) … -
Django + Nginx + Gunicorn site not working on Safari Browser
I made a website for a small business. Everything works fine on Chrome, Edge, etc. but on Safari it just pops out a Welcome to nginx! default message. I've configured the SSL with Certbot. Here's the configuration on nginx: listen 80; server_name ccomputercenter.com www.ccomputercenter.com; location /static/ { alias /home/cristi/SiteCMR/cmr_project/staticfiles/; } location /media/ { alias /home/cristi/SiteCMR/cmr_project/media/; } location / { proxy_pass http://unix:/home/cristi/SiteCMR/cmr_project/gunicorn.sock; 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; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/ccomputercenter.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/ccomputercenter.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 = www.ccomputercenter.com) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = ccomputercenter.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name ccomputercenter.com www.ccomputercenter.com; return 404; # managed by Certbot }``` I've read some other articles but I can't seem to find any exact information for this. Thank you all ! -
How can I hide the total count in changelist_view (Django admin)?
I want to hide the total displayed in changelist_view, as in the following image. Django admin screen I searched but couldn't find any way through admin customization. I know I can modify the template, but I wouldn't like to do it. Is this possible without changing the templates? -
Django-static-sitemaps errorTypeError: 'type' object is not iterable?
When using to generate a sitemap, I encountered a error when running the command. What is the cause of this error and how can I resolve it?django-static-sitemapsTypeError: 'type' object is not iterablepython manage.py refresh_sitemap **views.py** from django.contrib import sitemaps from . import models class WebSitemaps(sitemaps.Sitemap): changefreq = "weekly" priority = 0.5 def items(self): return models.ArticleModel.objects.all() def location(self, obj): return f"/{obj.aid}.html" **settings.py** STATICSITEMAPS_ROOT_SITEMAP = 'index.sitemaps.WebSitemaps'``` **urls.py** urlpatterns = [ re_path('^sitemap-baidu/', include('static_sitemaps.urls')), ] enter image description here -
Configuring Django and MinIO using HTTPS on same server
I have set up MinIO as my Django app object storage and integrate the functionality of this module on my the same server. I followed the instruction in django-minio-backend, but I got the below error. urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='subdomain.domain.org', port=9000): Max retries exceeded with url: /django-backend-dev-public (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1006)'))) A few contextual issues for the setup environment: The server runs Ubuntu 22.04 LTS operating system. the MinIO version is 2024-08-03T04-33-23Z. The Django version is 5.0.6 The MinIO setup worked perfectly when I had set it up to use unsecured connections (http), and Django running was running on the server unsecured. The Django web app could be able to upload files and images to MinIO server without any issue. The error started when I updated the MinIO setup to work using secured connections only. On the WebUI, the server loads using https perfectly (i.e. I can log onto the console using https://subdomain.domain.org:9000) The secure setup is done through linking the MinIO to the SSL certificate folder on the server (/opt/minio/certs) that contains both the public.crt and private.key The relevant lines for MinIO setup for my Django web-app in my settings.py are … -
Forbidden access to deployed Django website
I have deployed my django website, following Cirey Schafer tutorial (Python Django Tutorial: Deploying Your Application (Option #1) - Deploy to a Linux Server). But I have an error and I'm not sure why. I runned this: sudo tail -f /var/log/apache2/error.log error Current thread 0x00007f603fccb780 (most recent call first): <no Python frame> [Thu Aug 15 13:12:35.962154 2024] [wsgi:warn] [pid 72344:tid 140051363968896] (13)Permission denied: mod_wsgi (pid=72344): Unable to stat Python home /home/m_user/django_site/venv. Python interpreter may not be able to be initialized correctly. Verify the supplied path and access permissions for whole of the path. Python path configuration: PYTHONHOME = '/home/m_user/django_site/venv' PYTHONPATH = (not set) program name = 'python3' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = '/usr/bin/python3' sys.base_prefix = '/home/m_user/django_site/venv' sys.base_exec_prefix = '/home/m_user/django_site/venv' sys.platlibdir = 'lib' sys.executable = '/usr/bin/python3' sys.prefix = '/home/m_user/django_site/venv' sys.exec_prefix = '/home/m_user/django_site/venv' sys.path = [ '/home/m_user/django_site/venv/lib/python310.zip', '/home/m_user/django_site/venv/lib/python3.10', '/home/m_user/django_site/venv/lib/python3.10/lib-dynload', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' I get this when I run this ls -la total 40 drwxr-x--- 6 m_user m_user 4096 Aug 14 23:07 . drwxr-xr-x 3 root root 4096 Aug 14 … -
Can you safely update a Django AppConfig.label?
I'm in the process of merging two Django projects however they have conflicting app names. For example, the conflicting app names are customer, order, and product which are categorized into ecommerce and wholesale subdirectories. project ├── manage.py ├── apps │ └── ecommerce │ └── customer │ └── order │ └── product └── wholesale │ └── customer │ └── order │ └── product It's clearly stated in the docs for AppConfig.label that changing the label after migrations have been applied will cause breaking changes. I've tried creating an empty migration to manually rename the table then update the Model Meta app_label option however that seems to cause breaking changes as well. migrations.AlterModelOptions( name='Product', options={'app_label': 'wholesale_product'}, ), migrations.AlterModelTable( name='Product', table='wholesale_product_product', ), I feel like it should be easy to just rename the table. What's the best way to solve the name conflicts? Is there a way to do it without having to rename the apps and moving the models?