Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 5.1 models with fields using db_default throw on full_clean
Trying to implement Django 5's new db_default attribute for fields Using the following field as an example: editable = models.BooleanField(db_default=True) Would expect that if editable not specified when creating a new instance, that ORM would not throw error but would still save instance, and that the value of editable would be set to True at the database level. So executing the following to create a new object: product_obj = models.Product( id=id, name=name, is_active=is_active, inventory_type=inventory_type, leadtime=leadtime, ) product_obj.full_clean() product_obj.save() would be expected to succeed. Instead full_clean() raises a ValidationError: django.core.exceptions.ValidationError: {'editable': ['“<django.db.models.expressions.DatabaseDefault object at 0x151db1c70>” value must be either True or False.']} and similar behavior occurs throughout my codebase for any field for which db_default is set (CharField with choices, IntegerField, etc) Clearly I'm not understanding how db_default should be used. -
Read JSON Data from an incoming Django Request and Displaying the Data to HTML
I'm a month old of using Django and I want to create a Registration Form where the data will came from a POST Request (from a microreader that will throw a JSON data going to the Django View Endpoint). Once I received the response, I need to get the data_id and the user must input the name and its department, and displaying it as a form in the HTML that will be pushed to my database, once submitted. However, I'm having a hard time crafting this thing in views.py and its template. This is the thrown JSON Response: {"station":"XXXXXXXX","type":"TYPE-XXX","data_id":"9198491920"} This is the views.py @csrf_exempt def registration_form(request): if request.method == "POST": # Process the JSON data json_data = json.loads(request.body) dataid = json_data.get('data_id') # Initialize the form with the received dataid form = RegistrationForm(initial={'data_id': dataid) if form.is_valid(): name = form.cleaned_data['name'] department = form.cleaned_data['department'] return render(request,'registration.html',{'form':form}) else: # If GET request, initialize form form = RegistrationForm() return render(request, 'registration.html', {'form': form}) This is my registration.html. Although, you may not expect some things in my HTML since I'm trying all forms of displaying but there's no success. {% extends 'base.html' %} {% load static %} {% load widget_tweaks %} {% block content %} <form … -
Django i18n get_language_info_list and get_available_languages provide different language code
With {% get_current_language as CURRENT_LANGUAGE %} , {{ CURRENT_LANGUAGE }} shows nl-nl With {% get_available_languages as AVAILABLE_LANGUAGES %} , {{ AVAILABLE_LANGUAGES }} shows [('nl-NL', 'Nederlands'), ('en', 'Engels')] With {% get_language_info_list for AVAILABLE_LANGUAGES as LANGUAGES %} , {{ LANGUAGES }} shows [{'bidi': False, 'code': 'nl', 'name': 'Dutch', 'name_local': 'Nederlands', 'name_translated': 'Nederlands'}, {'bidi': False, 'code': 'en', 'name': 'English', 'name_local': 'English', 'name_translated': 'Engels'}] Settings: # https://docs.djangoproject.com/en/dev/ref/settings/#language-code LANGUAGE_CODE = "nl-NL" # https://docs.djangoproject.com/en/dev/ref/settings/#languages LANGUAGES = [ ('nl-NL', _('Dutch')), ('en', _('English')), ] In {{ LANGUAGES }} I expect code to be nl-NL and not nl. Anyone that can explain this discrepancy? Django version: Django==4.2.10 -
Temporal Workflow Issue in python: Response Not Returned, Queueing/Deadlock Occurs, Unable to Trigger New Workflow Unit Until Current One Finishes
I've created a workflow with 4 activity which runs one after another using temporalio, When my one workflow starts it not giving response, it is queued/Deadlock Occurs, Unable to trigger new workflow unit current one finishes. import asyncio import random import concurrent import multiprocessing from datetime import timedelta from temporalio.client import Client from temporalio.worker import Worker from temporalio import activity, workflow from temporalio.worker import SharedStateManager, Worker async def get_client(): client = await Client.connect("localhost:7233") return client @activity.defn async def activity1(params) -> dict: print("Inside activity 1") count = 1 while True: if count == 10000000000: break count = count + 1 return params @activity.defn async def activity2(params) -> dict: print("Inside activity 2") return params @activity.defn async def activity3(params) -> dict: print("Inside activity 3") return params @activity.defn async def activity4(params) -> dict: print("Inside activity 4") return params @workflow.defn class TestTemporalWorkflow: @workflow.run async def run(self, params) -> dict: response_1 = await workflow.start_activity( activity1, params, start_to_close_timeout=timedelta(seconds=100), ) response_2 = await workflow.start_activity( activity2, response_1, start_to_close_timeout=timedelta(seconds=100), ) response_3 = await workflow.start_activity( activity3, response_2, start_to_close_timeout=timedelta(seconds=100), ) response_4 = await workflow.start_activity( activity4, response_3, start_to_close_timeout=timedelta(seconds=100), ) async def main(params): task_queue = "demo-temporal-workflow-queue" workflows = [TestTemporalWorkflow] activities = [activity1, activity2, activity3, activity4] # Start client client = await get_client() async with … -
Is it possible to access a method decorator's information in Python?
I've designed a RBAC method in a Django project using the following concept: Declare an attribute permission_roles in the View/Viewset body This attribute receives information regarding the user roles that can access each method/action of the view (e.g.: 'create': (RoleChoices.ADMIN)) Then I had to think how to inform the frontend about role capabilities. I've thought of using a new model class Permission that stores an array of roles and have an unique name identifier (e.g.: Permission(action="user_management_list", roles=[1,2,3])) In order to populate this model, I've used the autodiscover Django's method + a decorator that goes above my view methods/actions: @allowed_roles('user_management_list', [RoleChoices.ADMIN]) def list(self, request, *args, **kwargs): return super().list(request, *args, **kwargs) Now I was thinking of a way to merge both functionalities, simplifying the RBAC custom permission by using the action name + the request user role and query directly to the DB (later I'll use also a cache strategy to reduce DB load). But the problem is, how could I access the decorator's first param (its the action name)? -
When I am running runserver command and the server starts and entering to the admin pannel there is an OperationalError
In models.py: # from email.policy import default # from pyexpat import model from django.db import models # from unicodedata import decimal from shortuuid.django_fields import ShortUUIDField from django.utils.html import mark_safe from userauths.models import CustomUser STATUS_CHOICE=( ("process","Processing"), ("shipped","Shipped"), ("delevered","Delevered"), ) STATUS=( ("draft","Draft"), ("disable","Disable"), ("rejected","Rejected"), ("In_review","In Review"), ("published","Published"), ) RATING=( (1,"⭐☆☆☆☆"), (2,"⭐⭐☆☆☆"), (3,"⭐⭐⭐☆☆"), (4,"⭐⭐⭐⭐☆"), (5,"⭐⭐⭐⭐⭐"), ) # Create your models here. def user_directory_path(instance,filename): return 'user_{0}/{1}'.format(instance.user.id, filename) class Category(models.Model): cid=ShortUUIDField(length=10,max_length=100,prefix="cat",alphabet="abcdef") title=models.CharField(max_length=100,default="Food") image=models.ImageField(upload_to="category",default="category.jpg") class Meta: verbose_name_plural="Categories" def catagory_image(self): return mark_safe('<img src="%s" width="50" height="50"/>'%(self.image.url)) def __str__(self): return self.title class Tags(models.Model): pass class Vendor(models.Model): vid=ShortUUIDField(length=10,max_length=100,prefix="ven",alphabet="abcdef") title=models.CharField(max_length=100,default="Nest") image=models.ImageField(upload_to=user_directory_path,default="vendor.jpg") description=models.TextField(null=True, blank=True,default="Normal Vendorco") address=models.CharField(max_length=100, default="6,Dum Dum Road") contact=models.CharField(max_length=100, default="+91") chat_resp_time=models.CharField(max_length=100,default="100") shipping_on_time=models.CharField(max_length=100,default="100") authenticate_rating=models.CharField(max_length=100,default="100") days_return=models.CharField(max_length=100,default="100") warranty_period=models.CharField(max_length=100,default="100") user=models.ForeignKey(CustomUser, on_delete=models.SET_NULL ,null=True) class Meta: verbose_name_plural="Vendors" def Vendor_image(self): return mark_safe('<img src="%s" width="50" height="50"/>'%(self.image.url)) def __str__(self): return self.title class Product(models.Model): pid=ShortUUIDField(length=10,max_length=100,prefix="prd",alphabet="abcdef") user=models.ForeignKey(CustomUser, on_delete=models.SET_NULL ,null=True) cagtegory=models.ForeignKey(Category, on_delete=models.SET_NULL ,null=True) title=models.CharField(max_length=100,default="Apple") image=models.ImageField(upload_to=user_directory_path,default="product.jpg") description=models.TextField(null=True, blank=True,default="This is a product") price = models.DecimalField(max_digits=10, decimal_places=2, default=1.99) old_price = models.DecimalField(max_digits=10, decimal_places=2, default=2.99) specifications=models.TextField(null=True, blank=True) tags=models.ForeignKey(Tags, on_delete=models.SET_NULL ,null=True) product_status=models.CharField(choices=STATUS, max_length=10,default="In_review") status=models.BooleanField(default=True) in_stock=models.BooleanField(default=True) featured=models.BooleanField(default=False) digital=models.BooleanField(default=False) sku=ShortUUIDField(length=10,max_length=100,prefix="sku",alphabet="abcdef") date=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(null=True,blank=True) class Meta: verbose_name_plural="Products" def product_image(self): return mark_safe('<img src="%s" width="50" height="50"/>'%(self.image.url)) def __str__(self): return self.title def get_percentage(self): new_price=(self.price/self.old_price) * 100 return new_price class ProductImages(models.Model): images=models.ImageField(upload_to="product-image",default="product.jpg") product=models.ForeignKey(Product, on_delete=models.SET_NULL ,null=True) date=models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural="Product Images" ######################################################Care,Order,CartItemsand Address########################### class CartOrder(models.Model): user=models.ForeignKey(CustomUser,on_delete=models.CASCADE) price= models.DecimalField(max_digits=10, … -
after connecting redis to django and docker, the data is not saved in redis-cli
I connected redis to django and did docker-compose, redis itself works, but if I want to connect to the terminal via docker exec -it redis redis-cli, then it connects, but I can’t get any data and if I write the keys * command, then no data either (except for celery) version: '3.8' services: web: build: . container_name: django ports: - "8000:8000" command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/app env_file: - .env environment: - DEBUG=1 - DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 - CELERY_BROKER=redis://redis:6379/0 - CELERY_BACKEND=redis://redis:6379/0 - REDIS_HOST=redis depends_on: - db - redis links: - db:db db: container_name: postgres image: postgres volumes: - ./data/postgres_data:/var/lib/postgresql/data environment: - POSTGRES_DB=${BD_NAME} - POSTGRES_USER=${BD_USER} - POSTGRES_PASSWORD=${BD_PASSWORD} - POSTGRES_HOST_AUTH_METHOD=trust expose: - '5432' redis: image: "redis:alpine" restart: always container_name: redis command: redis-server ports: - 6379:6379 celery: build: . command: celery -A wishes worker -l INFO volumes: - .:/app depends_on: - web - redis - db environment: - CELERY_BROKER=redis://redis:6379/0 - CELERY_BACKEND=redis://redis:6379/0 volumes: postgres_data: -
What is causing the route to change (ikely because form is submitting), i also added return false in the function?
I am currently building a single page web app and wanted that js handle the form submission and so that route remain the same. But when i click the submit button route changes, JS Code: document.addEventListener('DOMContentLoaded', function() { // Use buttons to toggle between views document.querySelector('#inbox').addEventListener('click', () => load_mailbox('inbox')); document.querySelector('#sent').addEventListener('click', () => load_mailbox('sent')); document.querySelector('#archived').addEventListener('click', () => load_mailbox('archive')); document.querySelector('#compose').addEventListener('click', compose_email); // By default, load the inbox load_mailbox('inbox'); }); function compose_email() { // Show compose view and hide other views document.querySelector('#emails-view').style.display = 'none'; document.querySelector('#compose-view').style.display = 'block'; // Clear out composition fields document.querySelector('#compose-recipients').value = ''; document.querySelector('#compose-subject').value = ''; document.querySelector('#compose-body').value = ''; } function load_mailbox(mailbox) { // Show the mailbox and hide other views document.querySelector('#emails-view').style.display = 'block'; document.querySelector('#compose-view').style.display = 'none'; // Show the mailbox name document.querySelector('#emails-view').innerHTML = `<h3>${mailbox.charAt(0).toUpperCase() + mailbox.slice(1)}</h3>`; } function send_mail(event){ const recipients = document.querySelector('#compose-recipients').value; const subject = document.querySelector('#compose-subject').value; const body = document.querySelector('#compose-body').value; //send the email as post to the server fetch('/emails', { method: 'POST', body: JSON.stringify({ recipients: recipients, subject: subject, body: body }) }) .then(response => response.json()) .then(result => { console.log(result); //loading the sent box after sending the email load_mailbox('sent'); }) return false; } document.querySelector('#compose-form').onsubmit = send_mail; HTML code: {% extends "mail/layout.html" %} {% load static %} {% block body %} … -
ImportError Django cannot import name 'SignupView'
So I imported the 'LoginView, LogoutView' but when I tried to import the 'SignupView' I got the following error: ImportError: cannot import name 'SignupView' from 'django.contrib.auth.views' (C:\Users\USER\Desktop\djang0\venv\Lib\site-packages\django\contrib\auth\views.py) This is what I believe to be the necessary code. #my views.py from django.contrib.auth.forms import UserCreationForm from django.shortcuts import render, redirect, reverse from django.core.mail import send_mail from django.views import generic from django.http import HttpResponse from.models import Lead, Agent from.forms import LeadForm, LeadModelForm class SignupView(generic.CreateView): template_name = "registration/signup.html" form_class = UserCreationForm def get_success_url(self): return reverse("login") #my app urls.py from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.contrib.auth.views import LoginView, LogoutView, SignupView from django.urls import path, include from leads.views import hero_page, HeroPageView urlpatterns = [ path('admin/', admin.site.urls), path('', HeroPageView.as_view(), name="hero-page"), path('leads/', include('leads.urls', namespace="leads")), path('login/', LoginView.as_view(), name="login"), path('logout/', LogoutView.as_view(), name="logout"), path('signup/', SignupView.as_view(), name="signup"), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) I don't know what to try, I'm kind of a beginner in Django. I've done a lot of research on multiple sites and articles but only person I've seen who had a similar problem had to remove the 'views' from the 'from django.contrib.auth.views' because they ran on an older version of Django which I believe to have been 2.0.1 but I'm … -
Python ImportError that puzzles me (already searched for similar stackoverflow posts with no luck)
I'm building an API with django ninja, for design reasons I'm using some logic inside microservice/logic/one_module.py that needs to get JSON data from microservice/service/repository.py This is my project structure: | .coveragerc | manage.py | pytest.ini | +---microservice | asgi.py | models.py | settings.py | urls.py | wsgi.py | __init__.py | +---logic | config.py | correlate.py | correlation_rules.py | generate_ticket.py | send_ticket.py | startup.py <--------- Code is being executed here | temp.py | __init__.py | | +---service | | application.py | | domain.py | | repository.py <--------- Data is here (must be imported) | | __init__.py | | | +---schemas | | application.py | | domain.py | | repository.py | | __init__.py | | | +---tests | | test_application.py | | test_domain.py | | test_logic.py | | test_repository.py | | __init__.py | | | +---json | alert_1.json | client_1.json | secrets_1.json | +---static | logo.png | script.js | styles.css | +---templates base.html email.html In service/repository.py I have: json_call = requests.get(...etc...) clients, alerts, secrets = ...comprehension to get the data as dict... In logic/startup.py I have: from microservice.service.repository import clients, secrets, alerts clients = ...some code using the data... Running it like that, it raises an error: Traceback (most recent call last): … -
Django ManyToMany not saving
I have a ModelMultipleChoiceField that I try to save save as ManyToMany relationships and tried almost every solution on the internet but for some reason I can't get mine to save. I don't get any errors and the rest of the form submits just not the ManyToMany. Models.py class Game(models.Model): players = models.ManyToManyField(Student, blank=True) other fields... class Student(models.Model): user_name = models.CharField(max_length=150, null=False, blank=False) Forms.py class Game(forms.ModelForm): players = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple(), queryset=Student.objects.all(), label="Players", required=False) Views.py def creategame(request): if request.method == "POST": form = Game(request.POST) if form.is_valid(): form.save() return redirect(reverse('management')) else: ... I tried multiple solutions like this, but none of them worked. Views.py def creategame(request): if request.method == "POST": form = Game(request.POST) if form.is_valid(): new_game = form.save(commit=False) new_game.save() form.save_m2m() return redirect(reverse('management')) else: ... -
NoReverseMatch: Reverse for 'login' not found. 'login' is not a valid view function or pattern name
I am sorry to post this problem once again. I am getting the error even though the configuration files looks correct with the 'login' entry. In settings.py added "LOGIN_URL = '/login/'" In the APP/templates/base.html: {% if user.is_authenticated %} <a href="{% url 'logout' %}">Logout</a> {% else %} <a href="{% url 'login' %}">Login</a> {% endif %} The APP/views.py looks as follows: from django.http import HttpResponse from django.template import loader from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required @login_required(login_url='login') # Redirect to the login page if not authenticated def protected_intro(request): return render(request, 'intro.html') The APP/urls.py looks like: from django.urls import path from django.contrib.auth.views import LoginView from . import views app_name = 'APP' urlpatterns = [ ... path('login/', LoginView.as_view(), name='login'), ] All the entries regarding the 'login' seems correct, but ending up with the error "Reverse for 'login' not found. 'login' is not a valid view function or pattern name." Please help. Thanks! I tried looking for the solution, but could not solve it. -
when I am running python manage.py make migrate there is an overflow error so which is causing an error
When I am running python manage.py makemigrations it worked but when I am running python manage.py migrate it is raising an overflow error # from email.policy import default # from pyexpat import model from django.db import models # from unicodedata import decimal from shortuuid.django_fields import ShortUUIDField from django.utils.html import mark_safe from userauths.models import CustomUser STATUS_CHOICE=( ("process","Processing"), ("shipped","Shipped"), ("delevered","Delevered"), ) STATUS=( ("draft","Draft"), ("disable","Disable"), ("rejected","Rejected"), ("In_review","In Review"), ("published","Published"), ) RATING=( (1,"⭐☆☆☆☆"), (2,"⭐⭐☆☆☆"), (3,"⭐⭐⭐☆☆"), (4,"⭐⭐⭐⭐☆"), (5,"⭐⭐⭐⭐⭐"), ) # Create your models here. def user_directory_path(instance,filename): return 'user_{0}/{1}'.format(instance.user.id, filename) class Category(models.Model): cid=ShortUUIDField(length=10,max_length=100,prefix="cat",alphabet="abcdef") title=models.CharField(max_length=100,default="Food") image=models.ImageField(upload_to="category",default="category.jpg") class Meta: verbose_name_plural="Categories" def catagory_image(self): return mark_safe('<img src="%s" width="50" height="50"/>'%(self.image.url)) def __str__(self): return self.title class Tags(models.Model): pass class Vendor(models.Model): vid=ShortUUIDField(length=10,max_length=100,prefix="ven",alphabet="abcdef") title=models.CharField(max_length=100,default="Nest") image=models.ImageField(upload_to=user_directory_path,default="vendor.jpg") description=models.TextField(null=True, blank=True,default="Normal Vendorco") address=models.CharField(max_length=100, default="6,Dum Dum Road") contact=models.CharField(max_length=100, default="+91") chat_resp_time=models.CharField(max_length=100,default="100") shipping_on_time=models.CharField(max_length=100,default="100") authenticate_rating=models.CharField(max_length=100,default="100") days_return=models.CharField(max_length=100,default="100") warranty_period=models.CharField(max_length=100,default="100") user=models.ForeignKey(CustomUser, on_delete=models.SET_NULL ,null=True) class Meta: verbose_name_plural="Vendors" def Vendor_image(self): return mark_safe('<img src="%s" width="50" height="50"/>'%(self.image.url)) def __str__(self): return self.title class Product(models.Model): pid=ShortUUIDField(length=10,max_length=100,prefix="prd",alphabet="abcdef") user=models.ForeignKey(CustomUser, on_delete=models.SET_NULL ,null=True) cagtegory=models.ForeignKey(Category, on_delete=models.SET_NULL ,null=True) title=models.CharField(max_length=100,default="Apple") image=models.ImageField(upload_to=user_directory_path,default="product.jpg") description=models.TextField(null=True, blank=True,default="This is a product") price = models.DecimalField(max_digits=10, decimal_places=2, default=1.99) old_price = models.DecimalField(max_digits=10, decimal_places=2, default=2.99) specifications=models.TextField(null=True, blank=True) tags=models.ForeignKey(Tags, on_delete=models.SET_NULL ,null=True) product_status=models.CharField(choices=STATUS, max_length=10,default="In_review") status=models.BooleanField(default=True) in_stock=models.BooleanField(default=True) featured=models.BooleanField(default=False) digital=models.BooleanField(default=False) sku=ShortUUIDField(length=10,max_length=100,prefix="sku",alphabet="abcdef") date=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(null=True,blank=True) class Meta: verbose_name_plural="Products" def product_image(self): return mark_safe('<img src="%s" width="50" height="50"/>'%(self.image.url)) def __str__(self): return self.title def get_percentage(self): new_price=(self.price/self.old_price) * … -
i am facing this error (1054, "Unknown column 'id' in 'erp_app_invoice'")
hello i am newbie in this field, at the beginning everything's worked fine however i faced this error (1054, "Unknown column 'id' in 'erp_app_invoice'") after making some changes in my models.py. notice that i dont have id in my models.py as it should be generated automatically as far as i know i tried adding id = models.AutoField(primary_key=True) but it didn't work due to the fact that i cant have 2 AutoFields, also tried to make it as CharField but that didn't work also -
Django project with Gunicorn, Nginx, Docker
I have a django app that runs fine locally (no DB). However, I need to deploy this into a VM using a docker image and am really new to everything for deployment and dont know how to start. Could anyone provide a step by step on how I can add gunicorn and nginx to the project and build everything into a docker image (i do not want to use docker-compose). Also looking on what the Dockerfile should have. Thanks -
DRF mixin uses the model manager's create method but not the update method
# models.py class HelloManager(models.Manager): ''' On create, set date_created and last_modified to the same values On update, set last_modified to current time ''' def create(self, *args, **kwargs): current_time = datetime.now() kwargs.setdefault('date_created', current_time) kwargs.setdefault('last_modified', current_time) return super().create(*args, **kwargs) def update(self, *args, **kwargs): kwargs['last_modified'] = datetime.now() return super().update(*args, **kwargs) The CreateModelMixin works just fine, but the UpdateModelMixin does not call my manager's update method. I went through DRF's implementation and found that the UpdateModelMixin calls serializer.save() wich calls either update or create but this is where I got lost. I tried just directly overriding perform_create like so: # views.py class HelloDetailView(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, generics.GenericAPIView): queryset = HelloModel.objects.all() lookup_field = 'id' def get_serializer_class(self): if self.request.method == 'POST': return HelloWriteSerializer return HelloReadSerializer def get(self, request, *args, **kwargs): return self.retrieve(request, *args, **kwargs) def post(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) def perform_update(self, serializer): HelloModel.objects.update(**serializer.validated_data) But the problem now is the UpdateModelMixin now returns old data. What's the best approach for this? -
Related fields aren't filtering in the formset (using library 'django-formset' )
I'm trying to use the library 'django-formset' to filter drop-down list (ForeignKey objects) when selecting an item in a linked drop-down list (related ForeignKey objects). I think, I did everything according to the instructions, but still the data in the second drop-down list is not filtered. Maybe someone has experience using this library with formset? What I did: Model class TypeCar(models.Model): title = models.CharField(max_length=20) class Car(models.Model): reg_mark = models.CharField(max_length=10) type_car = models.ForeignKey( 'TypeCar', ... ) class Order(models.Model): car = models.ForeignKey( Car, ... ) type_car = models.ForeignKey( TypeCar, ... ) Form (FormSet): from formset.widgets import Selectize class OrderCloseForm(forms.ModelForm): type_car = forms.ModelChoiceField( label="Type_car", queryset=TypeCar.objects.all(), widget=Selectize( search_lookup='name__icontains', placeholder="First, select Type car" ), required=False, ) car = forms.ModelChoiceField( label="Car", queryset=Car.objects.all(), widget=Selectize( search_lookup=['title__icontains'], filter_by={'type_car': 'type_car__id'}, placeholder="Then, select a Car" ), required=False, ) class Meta: model = Order fields = ( 'type_car', 'car', ) Formset displays already existing objects in which need to make a selection of the above fields OrderCloseFormSet = modelformset_factory( Order, form=OrderCloseForm, extra=0, can_delete=False, ) Template <head> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <link href="{% static 'formset/css/bootstrap5-extra.css' %}" rel="stylesheet"> <link href="{% static 'formset/css/collections.css' %}" rel="stylesheet"> <script type="module" src="{% static 'formset/js/django-formset.js' %}"></script> </head> <django-formset endpoint="{{ request.path }}" csrf-token="{{ csrf_token }}"> {{ formset.management_form }} {{ … -
Python Django does not see the CSS file
I just started using Django, which I initially had a lot of problems with, but that's not the point. I launched a new project about 4 times, it turned out that through the console it did not create a complete list of folders and files and I had to create them manually. I created and added an init file everywhere so that Python sees this folder, however, when I need to insert a Banner photo for my profile, when I start the server through the console and the python manage.py runserver command, although it launches my entire HTML structure, it does not display the photo , which I inserted there initially. I tried to change the location of the folders, I tried to change the location of the photos and it didn’t bring much results. Also, I changed settings.py and urls several times, but this also did not change anything, perhaps I made a mistake in the code or missed something? {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <link rel="stylesheet" href="{% static 'css' %}" /> <title>Your Profile</title> </head> <body> <div class="container"> <div class="sidebar"> <div class="logo"><span class="tf-logo">{{ title … -
Using an object attribute when accessing element in array in Django Template Python
So basically in my Django template I'm passing in two things from my view. a Django model object Plan which is defined like: class Plan(models.Model): class Sport(models.IntegerChoices): RUN = 1, "RUNNING" CYC = 2, "CYCLING" SWM = 3, "SWIMMING" sport = models.PositiveSmallIntegerField( choices=Sport.choices, default=Sport.RUN ) start_date = models.DateField("Starting Date") end_date = models.DateField("End Date") weeks = models.PositiveSmallIntegerField(default=0) title = models.CharField(max_length=20) description = models.TextField(max_length=100, blank=True, null=True) completed = models.BooleanField(default=False) def __str__(self): return self.title and 2. an array of arrays of strava activities pulled from an API, activity_list which is formatted so activity_list[i][j] would return week i's activity on day j. In my template, I need to access activity_list dynamically whilst looping through the week numbers in the plan. My first attempt was to do something like ativity_list.week.number.0 to access the Monday of the week we're on, but as expected Django treats week.number as a literal instead of replacing it with the number "0" or "3" or whatever. I'm really stuck on this so any help would be much appreciated, either with an ad-hoc fix or a way to refactor my models to make this feasible. Thanks -
CPU to 90% for gunicorn process on debian 11 - Django Nginx Gunicorn Supervisor
Since 3 days, I have some issues with the CPU usage which is up to 90%. When I run "top" on command line, I see that CPU usage for gunicorn is very high ! I do not have a lot of trafic on the website. I have checked the access log et error log, but I do not find anything... What Could I check to solve this performance issue ? Thanks I have checked the logs but I did not find anything. I work with Django, Nginx, Gunicorn and Supervisor. -
How to pass data to injected django template?
In django admin interface I have a custom tab for displaying a table. How to display the table as django admin model list table instead of field, but get the context for table from admin.py by calling the method from the model. I used django-baton's baton_form_includes to insert a template below the field, but then I could not pass data to that template. models.py class MyModel(TimeStampedModel): . . . def get_custom_tab_data(self): return OtherModel.objects.filter( active=False ) admin.py @admin.register(models.MyModel) class MyModelAdmin(): . . . readonly_fields = ( "get_custom_tab_data", ) fieldsets = ( _("Custom Tab"), { "fields": ("get_custom_tab_data"), "classes": ("tab-fs-custom") } ) . . # django-baton baton_form_includes = [("admin/custom_tab_template.html", "get_custom_tab_data", "below")] # This was the better solution but template table should display as model admin list with custom data, so had to use baton_form_includes to inject template above field. # def custom_tab_data(self, myModel: models.MyModel): # if myModel.active: # return "N/A" # if custom_data := myModel.get_custom_tab_data()[:15]: # get 15 latest # html_content = render_to_string( # "admin/custom_tab_template.html", # {"custom_data": custom_data} # ) # return mark_safe(html_content) @admin.display(description="Custom Tab") def get_custom_tab_data(self, myModel: models.MyModel): return self.custom_tab_data(account) custom_tab_template.html {% load i18n l10n %} <table class="table table-stripped"> <thead> <tr> <th>ID</th> <th>Name</th> <th>State</th> <th>Created</th> </tr> </thead> <tbody> {% comment %} {% … -
How to get parent model id in child serializer?
How to get parent id in child serializer? class Parent(models.Model): name = models.CharField('') date = models.DateField('') class Material(models.Model): name = models.CharField('') description = models.TextField('') parent = models.ForeignKey(Parent, on_delete=models.CASCADE) serializer = ParentSerializer(data=item) if serializer.is_valid(raise_exception=True): serializer.save() class MaterialSerializer(serializers.ModelSerializer): parent = ? class Meta: model = Material fields = ['id', 'name', 'description', 'parent'] class ParentSerializer(serializers.ModelSerializer): material = MaterialSerializer(many=True) class Meta: model = Parent fields = ['name', 'date', 'material'] I dont understand how get parent id in child serializer -
django-filter ModelMultipleChoiceFilter for product color with Preview
I'm honing my django skills by writing my own e-commerce web application from scratch and I want to let users see a preview for the product colors in the color filters. Here is what I currently have, which works perfectly: What I'm trying to achieve is this: My filters.py file: import django_filters from .models import Product,ProductColor class ProductFilter(django_filters.FilterSet): title = django_filters.CharFilter(lookup_expr='iexact') price_sale = django_filters.NumberFilter() price_regular= django_filters.NumberFilter() release_year = django_filters.NumberFilter(field_name='date_added', lookup_expr='year') release_year__gt = django_filters.NumberFilter(field_name='date_added', lookup_expr='year__gt') release_year__lt = django_filters.NumberFilter(field_name='date_added', lookup_expr='year__lt') chogoyo = ProductColor.objects.all() def colors(request): return ProductColor.objects.all() product_color = django_filters.filters.ModelMultipleChoiceFilter(queryset=colors) class Meta: model = Product fields = ['price_sale','price_regular', 'date_added','product_color'] What would be the best approach to accomplish this? Thank you in advance. -
"kombu.exceptions.OperationalError" occurs When running a server consisting of django, rabbitMQ, celery worker, and celery beat with docker-compose
Im currently trying to deploy a server consisting of django, rabbitMQ, celery worker, and beat. While celery beat executes the created periodic task well, the celery worker that executes the SMS sending task generates the above error message and does not work. version: "3.9" services: was_container: build: context: ./was dockerfile: Dockerfile.was container_name: was_container ports: - "8000:8000" env_file: - ./was/.env restart: always entrypoint: /entrypoint.sh networks: - miti_network rabbitmq: image: rabbitmq:3-management container_name: rabbitmq environment: - RABBITMQ_DEFAULT_USER=admin - RABBITMQ_DEFAULT_PASS=admin - RABBITMQ_DEFAULT_VHOST=/ ports: - "5672:5672" - "15672:15672" expose: - "15672" networks: - miti_network celery_worker: container_name: celery_worker build: context: ./was dockerfile: Dockerfile.celery-worker environment: - CELERY_BROKER_URL=amqp://admin:admin@rabbitmq:5672// depends_on: - was_container - rabbitmq networks: - miti_network command: celery -A config worker --loglevel=info --concurrency=1 celery_beat: container_name: celery_beat build: context: ./was dockerfile: Dockerfile.celery-worker environment: - CELERY_BROKER_URL=amqp://admin:admin@rabbitmq:5672// depends_on: - was_container - rabbitmq - celery_worker networks: - miti_network command: celery -A config beat --loglevel=info networks: miti_network: driver: bridge import os import dotenv from datetime import timedelta from celery import Celery dotenv.load_dotenv() os.environ.setdefault('DJANGO_SETTINGS_MODULE', f'config.settings.{os.getenv("ENVIRONMENT")}') app = Celery('MITI') app.config_from_object('django.conf:settings', namespace='CELERY') CELERYBEAT_SCHEDULE = { 'game_status_auto_update': { 'task': 'config.tasks.update_game_status', 'schedule': timedelta(minutes=1), }, } app.conf.update( CELERYBEAT_SCHEDULE = CELERYBEAT_SCHEDULE ) app.autodiscover_tasks() from .celery import app as celery_app __all__ = ['celery_app'] Please tell me the cause and how can … -
How to make a field unique across two models in Django without inheritance?
I have following 2 models, Admin and Employee: class Admin(models.Model): name = models.CharField(max_length=30) email = models.EmailField() city = models.CharField(max_length=30) def __str__(self): return str(self.name) class Employee(models.Model): name = models.CharField(max_length=30) email = models.EmailField() city = models.CharField(max_length=30) department = models.ForeignKey(Department, on_delete=models.CASCADE) def __str__(self): return str(self.name) What I want is to ensure that the field email is unique across both the models i.e. no two admins can have the same email AND no two employees can have the same email AND no admin and employee have the same email. I created a base class CustomUser and inherited it to both Employee and Admin class: class CustomUser(AbstractUser): email = models.EmailField(unique=True) class Employee(models.Model): name = models.CharField(max_lengt=30) email = models.OneToOneField(CustomUser, on_delete=models.CASCADE) city = models.CharField(max_length=30) department = models.ForeignKey(Department, on_delete=models.CASCADE) def __str__(self): return str(self.name) class Admin(models.Model): name = models.CharField(max_lengt=30) email = models.OneToOneField(CustomUser, on_delete=models.CASCADE) city = models.CharField(max_length=30) def __str__(self): return str(self.name) What I want to know is, is there any other way of ensuring this kind of cross-model uniqueness that wouldn't require me to create a separate Abstract class?