Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework data json comma separated django-taggit
I'm using django-taggit and django-taggit_serializer to tag my ecommerce products. When im making an update request via API when the json body looks like this {"tags":"dog,small,golden_retriever"} i get an error { "message": "failed", "details": { "tags": [ "Invalid json list. A tag list submitted in string form must be valid json." ] } } Although in django admin it is comma separated, i'd like to make it comma separated in django rest as well. Serializers class TagProductSerializer(TaggitSerializer, serializers.ModelSerializer): tags = TagListSerializerField() class Meta: model = Product fields = ('tags',) def update(self, validated_data): tags = validated_data.pop('tags') instance = super(TagProductSerializer, self).create(validated_data) instance.tags.set(*tags) return instance Views class TagProductsApiView(generics.UpdateAPIView): queryset = Product.objects.all() serializer_class = TagProductSerializer lookup_field = 'pk' def update(self, request, *args, **kwargs): instance = self.get_object() serializer = self.get_serializer(instance, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response({"message": "Tags have been updated successfully"}) else: return Response({"message": "failed", "details": serializer.errors}) -
Django Admin: How to use OneToMany Field inside list_display?
When listing the "House" Model inside the django admin panel i want to show all Houses but with the PostalCode inside list_display so i can sort them by postal code. Can i use the existing ForeignKey connection between House and HouseAddress to achieve this? I found some information on how to list parts of the "Houses" inside the "House Addresses" list view (because it has the foreign key field) but not from the "Houses" list view. Admin.py class HouseAdmin(admin.ModelAdmin): search_fields = ['Name'] list_display = ['Name'] class HouseAddressAdmin(admin.ModelAdmin): search_fields = ['PostalCode'] model = HouseAddress list_display = ['PostalCode'] Model.py class House(models.Model): Name = models.CharField(max_length=150, null=True, blank=False) class HouseAddress(models.Model): PostalCode = models.CharField(max_length=30, null=True, blank=True) AddressInfo = models.ForeignKey(House, null=True, blank=True, on_delete=models.CASCADE, related_name='fa') -
Date filter on model methods
Hi all this project I'm using python and Django. I currently have a two models where I writing model methods to show certain linked fields(FOREIGN KEYS) I will show this below, now what I am trying to do is be able to filter by date these model methods, from what I have tried I am getting an error no signature for built in methods. So basically my template renders these model methods and now I want to search between date ranges. The code below is my models and the methods as well as the function I am trying to filter these methods. Your feedback will be highly appreciated. #Sales agent model in models.py class SalesAgent(models.Model): user = models.OneToOneField(User,on_delete=models.SET_NULL,null=True,related_name="sauser") Team_leader = models.ForeignKey(TeamLeader,on_delete=models.SET_NULL,null=True,related_name="team_agent") SA_name = models.CharField(max_length=40) role = models.CharField(choices=Roles,default="default",max_length=13) def __str__(self): return self.user.username def sget_totals(self): today = datetime.date.today() return self.agent_sale.filter(Date_created__year=today.year,Date_created__month=today.month) def sget_confirmed(self): today = datetime.date.today() return self.agent_sale.filter(State="Confirmed",Date_created__year=today.year,Date_created__month=today.month) def sget_debi(self): today = datetime.date.today() return self.agent_sale.filter(AcknowledgeQA=True,State="Confirmed",Debi_status="Accepted",Date_created__year=today.year,Date_created__month=today.month) def sget_requested(self): today = datetime.date.today() return self.agent_sale.filter(Debi_status="Requested",Date_created__year=today.year,Date_created__month=today.month) def sget_cancelled(self): today = datetime.date.today() return self.agent_sale.filter(State="Cancelled",Date_created__year=today.year,Date_created__month=today.month) def sget_pending(self): today = datetime.date.today() return self.agent_sale.filter(State="Pending",Date_created__year=today.year,Date_created__month=today.month) #FILTERED SEARCH def sfget_totals(self): return self.agent_sale.all() def sfget_confirmed(self): return self.agent_sale.filter(State="Confirmed") def sfget_debi(self): return self.agent_sale.filter(AcknowledgeQA=True,State="Confirmed",Debi_status="Accepted") def sfget_requested(self): return self.agent_sale.filter(Debi_status="Requested") def sfget_cancelled(self): return self.agent_sale.filter(State="Cancelled") def sfget_pending(self): return self.agent_sale.filter(State="Pending") #THIS … -
django forms for adding new elements
I've got in views.py code for my view to add new docs to database: def doc_creation(request): # add_form = forms.DocAddForm(request.POST or None) if request.method == 'POST': add_form = forms.DocAddForm(data=request.POST) if add_form.is_valid(): new_doc = add_form.save(commit=False) rnd_nip=TestClass() new_doc.doc_client_nip = rnd_nip.random_client_nip() new_doc.added_by_2 = request.user new_doc.save() else: add_form = forms.DocAddForm() else: add_form = forms.DocAddForm() return render(request,'doc_new_2.html',{'add_form':add_form}) my model code is: class Doc(models.Model): doc_client_nip = models.CharField(blank=False,null=False,max_length=100,validators=[MinLengthValidator(10)],primary_key=True) doc_application_id = models.CharField(blank=False,null=True,max_length=100,validators=[MinLengthValidator(17)]) added_by_2 = models.ForeignKey(User, on_delete=models.CASCADE,null=True) TestClass() with its method random_client_nip() is used to generate random value of this field The problem is every time when I try to submit new record nothing is added to database page is reloaded to empty form but I don't receive any error. What is going on? Is the field added_by_2 problem? -
Models and forms in Django
Is forms and models run parallelly in Django? I've created a forms.py in my app and in that forms.py I've created a loginform insted of forms.py I've created AbstractUser and registration table in models.py , then import this loginform to models.py(from user_app.forms import LoginView). Then in forms.py import the models.py AbstractUser class.(I've named this class as user_type .. from user_app.models import user_type). I got this error File "D:\PROJECT\Digital-Vehicle-Project\digi_vehicle\user_app\models.py", line 7, in from user_app.forms import LoginForm File "D:\PROJECT\Digital-Vehicle-Project\digi_vehicle\user_app\forms.py", line 2, in from user_app.models import user_type ImportError: cannot import name 'user_type' from 'user_app.models' (D:\PROJECT\Digital-Vehicle-Project\digi_vehicle\user_app\models.py) -
Import local python packages elegantly?
I like approaches of local package management in Flutter/Dart and Rust very well, and hope there could exist some similar solution in Python. For example, I have a utility python package at /path/of/the/utility containing dozens of python files, and a myapp package at /path/to/my/app. For myapp to depend on utility, if I were using Flutter/Dart or using Rust, I could write down a line like: utility: path: /path/of/the/utility And then happily import it like import 'package:utility/somefile.dart. (The Rust case is similar so I do not repeat.) However, with Python, I have not found out such solution (pip does not seem to know this; neither is conda). Currently I have to use the following ugly approach: // myapp/somefile.py import sys sys.path.append('/path/of/the/utility') import utility and also manipulate my IDE (Intellij IDEA in my case) such that it understands this myapp package depends on utility package and do not give me a big red underline. Remark: It may not be possible (is it?) to let /path to be the package root and myapp to be a subpackage, because: (1) The myapp, for example, can be a Django project. (2) It will be hard to configure the ide (Intellij IDEA in my case) if … -
How to maintain a table of all proxy models in Django?
I have a model A and want to make subclasses of it. class A(models.Model): type = models.ForeignKey(Type) data = models.JSONField() def compute(): pass class B(A): def compute(): df = self.go_get_data() self.data = self.process(df) class C(A): def compute(): df = self.go_get_other_data() self.data = self.process_another_way(df) # ... other subclasses of A B and C should not have their own tables, so I decided to use the proxy attirbute of Meta. However, I want there to be a table of all the implemented proxies. In particular, I want to keep a record of the name and description of each subclass. For example, for B, the name would be "B" and the description would be the docstring for B. So I made another model: class Type(models.Model): # The name of the class name = models.String() # The docstring of the class desc = models.String() # A unique identifier, different from the Django ID, # that allows for smoothly changing the name of the class identifier = models.Int() Now, I want it so when I create an A, I can only choose between the different subclasses of A. Hence the Type table should always be up-to-date. For example, if I want to unit-test the behavior … -
Django ManyToManyField Model Manager
In my Python Django 3.7 source code I have the following models: class ExampleForeignKey(models.Model): name = models.Charfield(max_length=200) fields = models.ManyToManyField('ExampleField', related_name='example_foreign_keys') class ExampleField(models.Model): name = models.Charfield(max_length=200) I experience an issue with database duplication when using threading with the source code: example_field_obj = ExampleField(name='example_field_name') example_foreign_key_obj = example_field_obj.example_foreign_keys.get_or_create(name='example_foreign_key_name') I have managed to override the model manager get_or_create() method and applied a multithreading.Lock() in other cases where the model manager is being used directly in the case of direct 1:1 relationships however I don't know whether it is possible to apply the same principle in the case of ManyToManyField relationships? Apologies if this has been asked about before elsewhere - I can't seem to find much information on this particular issue. -
Celery task worker exits with WorkerLost exception and billiard.exceptions
I have celery running on a server with my Django app, the app is listening for data being posted and once data is posted it tosses that data to a celery task. In my django admin when a lot of data is sent the tasks end up failing by giving the error {"exc_type": "WorkerLostError", "exc_message": ["Worker exited prematurely: signal 9 (SIGKILL) Job: 134."], "exc_module": "billiard.exceptions"} I cannot figure out how to fix this, any help would be much appreciated -
Django problem to run python manage.py runservice
I tried to execute the commande under virtual environment: python manage.py runservice, it was still working yesterday, but then today when I run again, it shows all these Errors that I don´t understand what it means. My codes are correct, so I am lost. If anybody could help to explain me what shall I do please? output from cmd terminal enter image description here -
Django Rest Framework filtering a field with null and multiple values
I am using Django Rest Framework and want to filter the queryset in a view based on a certain field name. The filter values would be null and additionally any other particular value for the field blog_category which is a ForeignKey value. So filter query should be on two query params class Blog(ListCreateAPIView): permission_classes = [DjangoCustomModelPermissions] queryset = Blog.objects.all().select_related("blog_category") serializer_class = Blog_Serializer pagination_class = CustomPageNumberPagination filterset_fields = {'blog_category': ['isnull', 'exact', 'in']} I have added the lookup fields isnull to filter null values I have tried the following url requests but they do not work /blog/?blog_catgeory__in=1,null /blog/?blog_catgeory__in=1,isnull /blog/?blog_catgeory__in=1,isnull=true /blog/?blog_catgeory__in=1&blog_category__isnull=true How do I get this work? -
how to detect when web.whatsapp.com qrcode changes in webwhatsapi in django
I want my django application to load web.whatsapp.com so I obtained the page through a screenshot, but before the image get shown in the web page qrcode is reloaded. Please how can i reload the qrcode on my webpage through a screen shot as it is reloading in web.whatsapp. This is a sample of my code def qr_code_image(): whatapidriver.wait_for_login(90) . return HttpResponse(json.dumps({"whatapp_img":{"whats_img":"directory of the screenshot"}}), qr_code_image, content_type ="application/json", status=status.HTTP_200_OK) -
Django - possible to pass Model Enums into Template Javascript?
Is it possible in Django to pass in enum values from a model Django HTML Template - JS at bottom E.g. Can I in JS, do something like `var enumValue1 = "{{employment_ukrightowork_form.right_to_work_selection}}.UKRightoWorkSelection.PASSPORT" Django MODEL If my model in model.py looks like: # U.K. RIGHT TO WORK MODEL class UK_Right_To_Work(models.Model): class UKRightoWorkSelection(models.TextChoices): PASSPORT = 'Passport', _('U.K. or Irish - Passport') BIRTHCERT = 'Birth Certificate & N.I. Number', _('U.K. or Irish - Birth or Adoption Certificate + Proof of National Insurance Number') CERTOFREG = 'Certificate of Registration & N.I. Number', _('U.K. or Irish - Certificate of Registration or Naturalisation + Proof of National Insurance Number') right_to_work_id = models.BigAutoField(verbose_name='U.K. Right to Work ID', primary_key=True, serialize=False, auto_created=True) right_to_work_selection = models.CharField(verbose_name='U.K. Right to Work selection', max_length=41, choices=UKRightoWorkSelection.choices, blank=False, null=False, default=UKRightoWorkSelection.PASSPORT) -
ordery_by filter is not working properly in django
data = models.Booking.objects.filter(center__isnull=False,org_type='homedx').order_by('-created_at') return data.order_by( Case( When ( booking_status="resampling", then=Value(0) ), When ( booking_status="sample not received", then=Value(1) ), default = Value(1) ) ) created_at is DateTimeField in Booking Model. Here i have ordered by choice field and for that i have used Case, When and Value method from django.db.models. But when i am using this it is ignoring order_by created_at. I mean when these two conditions are met. i want to get the data in order of latest date. Why it is not working? Thank you !! -
Select2 widget showing on Django Admin site but not on the form template in Django4
I have two object models, NewsObject and StockObject. The stock object is a foreign key in the news object. class stockObject(models.Model): stock_name = CharField(max_length=100, blank=True, null=True) stock_tag = CharField(max_length=100, blank=True, null=True) def __str__(self): return self.stock_name class newsObject(models.Model): title = CharField(max_length=100, blank=True, null=True) body = TextField(blank=True, null=True) stock = ForeignKey(stockObject, on_delete=models.SET_NULL, blank=True, null=True) I have used autocomplete_fields property in the ModelAdmin class as I want a searchable dropdown for stocks in news. I have also added search_fields in the stocks ModelAdmin as mentioned in the documentation. This is what my admin.py looks like: class stockAdmin(admin.ModelAdmin): list_display = ['stock_name', 'stock_tag'] search_fields = ['stock_name'] class newsAdmin(admin.ModelAdmin): list_display = ['title', 'body', 'stock'] search_fields = ['title', 'body', 'stock'] autocomplete_fields = ['stock'] Now, the issue is that I get a searchable dropdown on the Django Admin site for this field, but it is only a dropdown (not searchable) on the actual template screen. I have a basic view which calls the template, like so: Views.py def createNews(request): form = NewsForm() if request.method == 'POST': form = NewsForm(request.POST) if form.is_valid(): form.save() return redirect('/backoffice/') context = {'form' : form} return render(request, 'NewsForm.html', context) And NewsForm.html is: {% extends "base.html" %} {% load static %} {% block content %} … -
how to get users id in django model?
I need to get id from logged user to filter query in models.how to get users id in django model? Thanks in models.py: class Portfo(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True) sell = models.ForeignKey(Sell, on_delete=models.CASCADE, null=True) customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True) profit = models.PositiveIntegerField(null=True) final_amount = models.IntegerField(null=True) def __str__(self): return self.product.name def final_amount(self): final_amount = 0 buy = Buy.objects.filter(product_id=self.product.id, owner__exact=...) sell = Sell.objects.filter(product_id=self.product.id) -
django-crontab job not running on developement server
I have the following task in cron.py. from coreapp.models import Event, User def update_survey_summary(): print("starting") u = User.objects.get(email="admin@email.com") e = Event( creator=u, title="Some event", location="Some location", hosted_by="Admin" ) print("saving...") e.save() And here are crontab config in settings.py: CRONJOBS = [ ('*/5 * * * *', 'coreapp.cron.update_survey_summary') ] INSTALLED_APPS = [ "django_crontab", ... Basically, the idea is to insert a record every 5 minutes. But nothing happens, and if use python manage.py crontab run <hash>, the job runs successfully and indeed does insert a record in the database. What am I missing? -
Django login integration with Microsoft AD
I successfully managed to integrate Microsoft Azure AD login on my Django site, but how do i make it such that users are always logged out after the browser is closed (i.e. have to login using Microsoft AD each time they access the site)? I dont know how to integrate Django sessions with request.identity_context_data -
How to fix AttributeError at /login/ 'NoneType' object has no attribute 'lower'
I am trying to create a login form in Django. In that form, there are 2 fields, username, and password for login. Now I have used lower() at the time of getting the username. Have a look at the code below. I have used lower() because if an user enters the upper case letter they don't have to face any problem. Here is the code def loginForm(request): page = 'login' if request.user.is_authenticated: #if user is already login, restricted to visit the login page again return redirect('home') if request.method == 'POST': username = request.POST.get('username').lower() password = request.POST.get('password') try: user = User.objects.get(username=username) except: messages.error(request,'User does not exist') user = authenticate(request,username=username, password=password) if user is not None: login(request, user) return redirect('home') else: messages.error(request,'Invalid Username or Password') context = {'page':page} return render(request, 'base/register_login.html',context) here is the SS of the error.. Screenshot of the error in the code Kindly let me know how can I solve this error.. -
Submit a form only once in Django
I am trying to make the user submit a form only once. I have a /dashboard page which is shown after submitting the /petform. But, I want the user to submit the form only once after logging in and other times it should redirect to the /dashboard directly (or show a message that "form already submitted"). models.py class PetFormData(models.Model): abstract = True name = models.CharField(max_length=100) age = models.IntegerField() breed = models.CharField(max_length=100) amount_spent = models.CharField(max_length=100, choices=AMOUNT_CHOICES) pincode = models.CharField(max_length=15) services_required = models.CharField(max_length=100, choices=SERVICE_CHOICES) auth_user_email = models.ForeignKey(User, on_delete=models.CASCADE) form_submitted = models.BooleanField(default=False) views.py @login_required def showformdata(request): form = PetForm(request.POST) if request.method == 'POST': if not PetFormData.form_submitted and user == PetFormData.auth_user_email: PetFormData.form_submitted = True print(PetFormData.form_submitted) if form.is_valid(): user = request.user nm = form.cleaned_data['name'] age = form.cleaned_data['age'] breed = form.cleaned_data['breed'] am_sp = form.cleaned_data['amount_spent'] pin = form.cleaned_data['pincode'] ser_req = ','.join(form.cleaned_data['services_required']) model_pet_form = PetFormData(name=nm, age=age, breed=breed, amount_spent=am_sp, pincode=pin, services_required=ser_req, auth_user_email=user) model_pet_form.save() print(session_data) return redirect('/dashboard') else: print(PetFormData.form_submitted) return HttpResponse('Form already submitted', content_type="text/plain") else: form = PetForm() return render(request, 'petform.html', {'form': form}) -
How to overwrite Django Admin result_list?
Django newbie here.. I am working on a projects that I need to do search in Django Admin Panel. I have a model named SearchModel and it has colums named "id", "word" and an object called Desert and this object has '1' as id I have another model named Result000 ('000' refers to the first three letters of md5 of Desert). It has columns named "id", "word_id", "score", "title" and has an object named "Sahara Desert" whose "word_id" is the same as the id of the "Desert" object in the first table. No ForeignKey or any other relation types between those table's items here's the question: When I search for Desert in SearchModel's search field. I want to list all objects in table Result000 which have same word_id as id of "Desert" object in SearchModel When I search for Desert in SearchModel's search field. I want to list all objects in table Result000 which have same word_id as id of "Desert" object in SearchModel here's my current code: # root/admin.py class BookAdmin(admin.ModelAdmin): def __init__(self, model, admin_site): self.list_display = [field.name for field in model._meta.fields] self.search_fields = [field.name for field in model._meta.fields] self.temp_model = "SearchModel" self.temp_term = "" self.word_id = None self.search_term … -
CSRF verification failed. Request aborted. After deploy to cloud
I wrote a Django application and after I developed put it to a Docker container and deploy it to Google Cloud Run. The server is OK and run but when I want to type something in the forms and submit it I got this error: Forbidden (403) CSRF verification failed. Request aborted. What's the problem with it? Should I add something besides the csrf_token? Here's my views.py: from django.shortcuts import render, redirect from . models import Action ##from django.core.mail import send_email def index (request): actions = Action.objects.all() return render(request, 'index.html', {"actions": actions}) def uj_szemely (request): if request.method == "GET": return render(request, 'uj_szemely.html') elif request.method == "POST": surname = request.POST.get('surname') lastname = request.POST.get('lastname') whatdo = request.POST.get('whatdo') done = request.POST.get('done') created = request.POST.get('created') deadline = request.POST.get('deadline') if done == 'on': done = True else: done = False formaction = Action(surname=surname, lastname=lastname, whatdo=whatdo, done=done, created=created, deadline=deadline) formaction.save() return redirect('fooldal') def fooldal (request): return render(request, 'fooldal.html') My models.py: from pyexpat import model from django.db import models class Action (models.Model): surname = models.CharField(max_length=100) lastname = models.CharField(max_length=100) whatdo = models.TextField() done = models.BooleanField(default=False) created = models.DateField(auto_now_add=True) deadline = models.DateTimeField() I also have a contact page on the website and the contact's form is giving the same … -
Change layout of django-filter form
I am currently working on my first bigger django project and I am facing issues regarding the layout of my data filters made with django-filters. The default layout of the django-filter form is a vertical list (see image), but I need to make it horizontal, consisting of two rows (labels/fields). What is the (best practice) way to edit the layout? Is there a way I can access every Label/Field-Item of the form from within the template, so I can use Bootstrap5 Grid? One restriction is, that my template will be used by differents models/filters, so I need to configure the layout dynamically. Every hint is very much appreciated :) Thank you! My template (relevant section) <form method="get" class="form"> <button type="submit" class ="btn btn-primary">Filtern</button> {% crispy filter.form %} </form> my django-filter filter class class EquipmentFilter(FilterSet): class Meta: model = Equipment fields = {'name': ['icontains'], 'description': ['icontains']} my model class Equipment(models.Model): """Device that can execute a measurement""" name = models.CharField("Name", max_length=50) description = models.CharField("Description", max_length=100) configuration = models.JSONField("Configuration", default=dict) equipment_category = models.ForeignKey("EquipmentCategory", on_delete=models.CASCADE, verbose_name="Equipment Category") -
How to Solve IImportError in Django?
I'm new to django and I'm facing some difficulties in creating a user from the AbstractUser model. Now I'm starting wondering if my user model is not being build in the right way. This is my Owner model from django.contrib.auth.models import AbstractUser from django.db import models from django.db.models import CASCADE, BooleanField from user_app.forms import LoginForm class user_type(AbstractUser): is_user = models.BooleanField('Is user', default=False) is_police = models.BooleanField('Is police', default=False) is_insurance = models.BooleanField('Is insurance', default=False) is_rto: BooleanField = models.BooleanField('Is rto', default=False) class Owner(models.Model): user_id = models.AutoField(primary_key=True) login_id = models.ForeignKey(LoginForm, on_delete=models.DO_NOTHING) user_name = models.CharField(max_length=255) aadhar_number = models.CharField(max_length=16) photo = models.FileField() mobile = models.IntegerField() licence = models.CharField(max_length=10) address = models.TextField() state = models.CharField(max_length=10) district = models.CharField(max_length=10) city = models.CharField(max_length=10) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) objects = models.Manager() and there another import error occurred in forms.py. this is my form.py from django import forms from user_app.models import user_type class LoginForm(forms.Form): username = forms.CharField( widget=forms.TextInput( attrs={ "class": "form-control" } ) ) password = forms.CharField( widget=forms.PasswordInput( attrs={ "class": "form-control" } ) ) class Meta: model = user_type fields = ('username', 'email', 'password1', 'password2', 'is_user','is_insurance', 'is_police', 'is_rto') and when I'm running this project using 'python manage.py runserver' then it shows File "D:\PROJECT\Digital-Vehicle-Project\digi_vehicle\user_app\models.py", line 7, in <module> from user_app.forms … -
facing problems with psycopg2 django
My python version is 3.10 and postgre version is 14 I am working on django, there I got an issue that is: my settings.py 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'testdb', 'USER': 'postgres', 'PASSWORD': 'xxxx', 'HOST': '127.0.0.1', 'PORT': '5432', } } when I write this command; python manage.py runserver it says, Error loading psycopg2 module: No module named 'psycopg2' then I run the command to install psycopg2 pip install psycog2 successfully installed the psycopg2 but after I run the python manage.py runserver it shows the error; AssertionError: database connection isn't set to UTC I found the solution that downgrade your psycopg2 version to 2.8.6 So I uninstall and run the command again; pip install psycopg2==2.8.6 but after that, it shows the error when I run the server Error loading psycopg2 module: DLL load failed while importing _psycopg: The specified module could not be found. please help me with that I am new to python thanks in advance