Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Disable Django admin buttons after click
Is there any easy way in Django change forms to disable buttons after submit. I want to prevent users from submitting the form twice at the same instant! -
Mysql CHARSET is set to utf8mb4, but insert emoji always raise Error 1366
First, check database CHARSET: MariaDB [outdoors]> show create database outdoors; | outdoors | CREATE DATABASE outdoors /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci */ | Then check the table CHARSET: MariaDB [outdoors]> show create table backend_comment; | backend_comment | CREATE TABLE backend_comment ( id bigint(20) NOT NULL AUTO_INCREMENT, geo varchar(10) DEFAULT NULL, content varchar(250) NOT NULL, img varchar(100) DEFAULT NULL, comment_id int(11) DEFAULT NULL, create_time datetime(6) NOT NULL, notify_id bigint(20) NOT NULL, to_id int(11) DEFAULT NULL, user_id int(11) NOT NULL, PRIMARY KEY (id), KEY backend_comment_notify_id_61aef760_fk_backend_notify_id (notify_id), KEY backend_comment_to_id_4dd23479_fk_auth_user_id (to_id), KEY backend_comment_user_id_1ab394ea_fk_auth_user_id (user_id), CONSTRAINT backend_comment_notify_id_61aef760_fk_backend_notify_id FOREIGN KEY (notify_id) REFERENCES backend_notify (id), CONSTRAINT backend_comment_to_id_4dd23479_fk_auth_user_id FOREIGN KEY (to_id) REFERENCES auth_user (id), CONSTRAINT backend_comment_user_id_1ab394ea_fk_auth_user_id FOREIGN KEY (user_id) REFERENCES auth_user (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci | Test insert emoji content: MariaDB [outdoors]> insert into backend_comment (id, content, notify_id, user_id, create_time) values (1, 'insert emoji test 😊 ', 1, 1, NOW()); ERROR 1366 (22007): Incorrect string value: '\xF0\x9F\x98\x8A' for column outdoors.backend_comment.content at row 1 So what's the problem? help me please 😂 More information: Server version: 10.11.8-MariaDB-0ubuntu0.24.04.1 Ubuntu 24.04 -
'Invalid filter: 'length_is' Error in Django Template – How to Fix?
I’m encountering a TemplateSyntaxError in my Django project when rendering a template. The error message I’m seeing is: TemplateSyntaxError at /admin/dashboard/program/add/ Invalid filter: 'length_is' Django Version: 5.1 Python Version: 3.12.4 Error Location: This error appears in a Django template at line 22 of the fieldset.html file. {% for line in fieldset %} {% for field in line %} {{ field.field.label|capfirst }} {% if field.field.field.required %} * {% endif %} What I Tried: Checked for Custom Filters: I reviewed my project and its installed packages to verify if there is a custom filter named length_is. I found that no such custom filter is defined in my project. Verified Django Installation: I ensured that Django is correctly installed and up-to-date with version 5.1. Reviewed Template Code: I carefully examined the template code that causes the error. I found that line.fields|length_is:'1' is used, but the length_is filter is not a standard Django filter. Searched for Package Bugs: I searched through documentation and bug reports related to django-jazzmin to see if there is any mention of the length_is filter issue, but I could not find relevant information. What I Expected: I expected to find either: Documentation or a reference indicating that length_is is a … -
JS / Jquery - Dynamically set text value to a Django form choicefield
I have this choicefield in a django form : forms.py sales_documents_description_1 = forms.ChoiceField(required=False, choices=list(models_products.objects.values_list( 'id_product','product_denomination')), widget=forms.Select(attrs={'id': 'sales_documents_editable_select_description_1','style': 'width:200px','onchange': 'populate_selected_product(this.id,this.value)'})) In my template, how do I set this choicefield value by specifiying the text argument (NOT THE VALUE) I tried with this : Template.html $('#sales_documents_description_1').filter(function() {return $(this).text() == 'Neumann U87';}).prop('selected', true); But it's not working. Any JS or JQuery solution will be ok for me. Thanks -
Filtrer les données d'un select à partir d'un autre select
Bonjour. Je suis entrain de développer une petite application de gestion scolaire en Django. Sur mon formulaire j'ai 3 drop-down : un pour afficher la liste des filières, un autre pour afficher la liste de classe selon la filière sélectionnée et un autre pour afficher la liste des élèves inscrits dans la classe sélectionnée précédemment dans la liste des classes affichées selon la filière choisie. Aidez-moi avec le code pour résoudre ce problème. Je travaille en Django 5. J'ai besoin d'avoir des filtres sur mes modèles Classe et Eleve pour y arriver mais je ne sais pas comment procéder. -
TemplateSyntaxError after Adding Django Admin Theme using Jazzmin Module
I've added a Django admin panel theme to my project using the django-jazzmin module. It works fine initially, but when I try to access certain options in the admin panel (like "Users" or "Profile"), I encounter the following error: TemplateSyntaxError at /admin/booking/bookedseat/53/change/ Invalid filter: 'length_is' and this is my html code <div class="form-group{% if line.fields|length_is:'1' and line.errors %} errors{% endif %}{% if not line.has_visible_field %} hidden{% endif %}{% for field in line %}{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% endfor %}"> From what I've read online, it seems like the theme might be deprecated or not fully compatible with Django 5, but I'm not entirely sure. I'm currently stuck and not sure how to resolve this issue. Has anyone else faced this problem? Any advice on how to fix this template error or suggestions for alternative themes that work well with Django 5? Details: Django version: 4.2 Jazzmin version: django-jazzmin-3.0.0 Thanks in advance for any help! Questions: Has anyone encountered this issue with Jazzmin on Django 5? Is there a known fix or workaround to resolve this length_is filter error while still using Jazzmin? Would downgrading Django or making adjustments to the Jazzmin templates be a viable solution? -
GitHub Actions not picking-up errors on Django doctests
I just realized that failure of my doctests was not raising error during testing run through GitHub Actions. How to ensure that failing doctests would trigger failure of the GitHub Actions testing? Example of a doctest as I'm defining them so far: from django.test import SimpleTestCase import doctest class DocStrings_Tests(SimpleTestCase): def test_docstrings(self): from cubes import color_coding doctest.testmod(color_coding) and here is the simplified workflow I'm using for testing: name: Project testing on: [pull_request, push] # activates the workflow when there is a push or pull request jobs: run_project_testing: runs-on: ubuntu-20.04 strategy: fail-fast: false matrix: tests: ["cubes", "users", "games"] steps: - name: Run Tests - ${{ matrix.tests }} run: | pip install coverage coverage run -p manage.py test ${{ matrix.tests }} -
django RelatedManager return None in template
I am trying to access related data in Templates But I only get None. models from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Product(models.Model): title = models.CharField(max_length=50) description = models.TextField() price = models.PositiveBigIntegerField() discount = models.PositiveBigIntegerField(default=0) inventory = models.PositiveBigIntegerField(default=1) last_update = models.DateTimeField(auto_now_add=True) def __str__(self) -> str: return self.title class Image(models.Model): image = models.ImageField() product = models.ForeignKey(to=Product,on_delete=models.CASCADE) class Cart(models.Model): STATUS = [ (0,"pending payment"), (1,"paid") ] status = models.SmallIntegerField(choices=STATUS,default=0) user = models.ForeignKey(to=User,on_delete=models.CASCADE) created = models.DateTimeField(auto_now=True) def __str__(self) -> str: return f"{self.user} - {self.status}" @receiver(post_save,sender=Cart) def cart_post_save(sender, instance, created, *args, **kwargs): if created and instance.status == 1 : Cart.objects.create(user=instance.user) class Order(models.Model): product = models.ForeignKey(to=Product,on_delete=models.CASCADE) count = models.PositiveIntegerField(default=0) cart = models.ForeignKey(to=Cart,on_delete=models.CASCADE) def __str__(self) -> str: return f"{self.product}" views from django.views import generic from . import models from django.http import JsonResponse,HttpResponseBadRequest,HttpResponse class ProductsList(generic.ListView): """return list of all products and template name is prudoct_list.html""" model = models.Product paginate_by = 30 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context class ProductsDetail(generic.DetailView): """return a product and template name is prudoct_detail.html""" model = models.Product def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>online-shop</title> … -
'utf-8' codec can't decode byte 0xff in position 0: invalid start byte [Djanago Rest Framework]
Issue: When uploading data with an image, the following issue occurs if some PrimaryKeyRelatedField is missing or the field ID is not valid. If I don't upload any image file, then expected output field validation issues arise. Encountered Issue: If I send some missing or invalid data with image files, the following issue occurs. However, the expected result was a validation issue. Validation Issue [expected output]: The API shows the following output if I don't send any image file, which is the expected output. { "status": false, "errors": { "service_cost_details": [ "This field is required." ], "photo": [ "No file was submitted." ], "citizenship_front": [ "No file was submitted." ], "citizenship_back": [ "No file was submitted." ], "province": [ "Invalid pk \"75242546\" - object does not exist." ] }, "results": { "house_number": "420", "old_membership_number": "", "first_name": "test", "middle_name": "test", "last_name": "456", "email": "user@example.com", "phone_number": "9895655644", "address": "madhyabindu", "date_of_birth": "2024-08-15", "gender": "Male", "pan_number": "420", "family_member_count": "4", "citizenship_number": "56551", "citizenship_issue_district": "1", "province": "75242546", "district": "2", "municipality": "3", "ward": "4", "tol": null } } My model Looks like: class ConsumerDetails(CreatorModifierInfo): gender_select = (("Male", "Male"), ("Female", "Female"), ("Other", "Other")) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True, db_index=True) office = models.ForeignKey(Office, null=True, blank=True, on_delete=models.SET_NULL) service_cost_details = models.ForeignKey(ServiceCostDetails, … -
Running another method in a View after a form is saved using CBVs - DJANGO
I am trying to run another method after a form is saved: The method inc_rec gets the id field created from the class based view once saved Once form is saved: I want to retrieve all records in the table Checklist Iterate through each of the rows and add the records to the All_Inspection table and updating the company id. I am a bit stuck - as I have tried using signals, and I have tried to override, but somewhere there is a gap. Help appreciated - Thanks in advance. class ParishCreateView(LoginRequiredMixin, CreateView): model = Company fields = ['str_Company_Name', 'str_City','str_post_code'] #success_url = '/' def form_valid(self, form): print('form_valid') form.instance.author = self.request.user return super().form_valid(form) def inc_rec(self): Checklist = Checklist.objects.all() id = self.request.id for rec in Checklist: new_rec=All_Inspection(str_status=rec.str_status, str_check=rec.str_check, str_comment='',company_id=id) new_rec.save() I am expecting new records to be added into ALL_Inspection table once the form is saved with the new created item. -
Django All-auth return account inactive at the first social login
I have the local account that status is_active = False. Now I would like to set the account activation status True automatically if users login by their social account. At my code, I have the Django Allauth hook to set the user is_active to True class CustomAccountAdapter(DefaultSocialAccountAdapter): def pre_social_login(self, request, sociallogin): email = sociallogin.email_addresses[0] user = User.objects.get(email=email) user.is_active = True user.save() However, at the first time login, it's always tells me that the account is not active. When login at the second time, users can login as expected, I'm still not figure out why is this happening. please help me with this, thank you.