Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to execute a django query with group by, alongwith multiplying two columns?
I have data like this product type quantity price/quantity chocolate buy 2 100 chocolate buy 4 200 colddrink buy 3 300 chocolate sell 3 200 colddrink buy 1 100 now I want to group the data by product and its type, and the quantity should be equal to total quantity for the particular type. While total price should be equal to (price(at which it was bought/sold) * quantity) for eg. aggregated result should be like for above table product type quantity total price chocolate buy 6 1000 chocolate sell 3 600 colddrink buy 4 1000 so far I've tried to do this Product.objects.values('product', 'type').annotate(quantity = Sum('quantity'),price = Sum('price', field='price*quantity) it would return <QuerySet [{'product': 'chocolate', 'type': 'buy', 'quantity': 6, 'price': 300.0}, {'product': 'chocolate', 'type': 'sell', 'quantity': 3, 'price': 200.0}, {'product': 'colddrink', 'type': 'buy', 'quantity': 4, 'price': 400.0}]> As you can see, it just sums the price instead of multiplying with quantity. Anything I'm doing wrong, or anyone can suggest how to do this? -
How to debug a Django app with PYCHARM Community Edition
i'm trying to debug a Django application on Pycharm Community Edition 2020.3, but can't because the breakpoints are NOT reaching or activating. I followed a YouTube tutorial and this stack overflow post for configuring a debugging session on Django , both have the same steps. I'll attach a screenshot of the configuration of my debugging session: click here (sorry stack overflow doesn't allow me to show it directly) Any ideas, comments or thoughts. I'm new to Python and Django so please have patient with me.PS: this is my first time debugging an application on Pycharm, i did try debugging on Vscode and indeed works, but i rather use Pycharm -
Django admin - limit choices of a many to many field to already selected objects
I have a model with a many to many field and want to limit the choices in the django admin detail view to the ones already selected and allow new ones to be added. I tried the following: #admin.py ... class DocumentAdminForm(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["followups"].queryset = kwargs["instance"].followups.all() class DocumentAdmin(admin.ModelAdmin): form = DocumentAdminForm ... followups is the name of the many to many field. The filter works as expected for already selected objects but I get the following error when I try to add a new object or remove one: Select a valid choice. <OBJECT ID> is not one of the available choices. Am I missing something with the form or do I need to do this in another way. I thought of limit_choice_to in the model but don't know how to get the right filter for this case. I am using django 3.1 -
saving one value in two separate model field drf
so I am trying to save same value in two fields in same model .. to give an example : my models.py will contain following fields profile_img = models.ImageField("Profile Image", blank=True, null=True) first_img = models.FileField("First Image", blank=True, null=True) and my serializer.py class SomeSerializer(serializers.ModelSerializer): class Meta: model = Some fields = ( 'id', 'username', 'first_img', ) my views.py class user_api_v2(APIView): parser_classes = (MultiPartParser, FormParser) def post(self, request, format=None): serializer = SomeSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Is there any way I can save the same instance of first_img to profile_img while posting ? -
Django-rest-framework field validation error is not getting raised
I tried to validate image for their extension and size and my ultimate goal is if image not valid then raise validation error but in my case another error occurred like that : UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte models.py: class UserPhoto(models.Model): user = models.ForeignKey(to = User,on_delete = models.CASCADE,related_name='userPhoto') image1 = models.ImageField(upload_to = 'upload_image1') image2 = models.ImageField(upload_to = 'upload_image2',blank = True,null = True) description = models.TextField(null = True,blank=True) ... created_date = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s_%s' %(self.id,self.user) def image_tag1(self): return mark_safe('<img src="%s" width="80px" height="80px" />' % (self.image1.url)) image_tag1.short_description = 'Image__1' if image2: def image_tag2(self): return mark_safe('<img src="%s" width="100px" height="100px" />' % (self.image2.url)) image_tag2.short_description = 'Image__2' If image extension is invalid then test(see my below code) variable return None value(here I use any path for testing purpose). imghdr--Determine the type of an image serializer.py: import imghdr class PhotoUploadSerializer(serializers.ModelSerializer): username = serializers.CharField(source='user.username',read_only=True) image1 = serializers.ImageField(max_length=None, use_url=True) def validate_image1(self, image): # 12MB MAX_FILE_SIZE = 12000000 test = imghdr.what(r'C:\Users\Pradip\Documents\Django project\patrepedia\backend\patrepedia\photos\serializers.py') ____print(test,"okkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk") this | if test is None: part | if image.size > MAX_FILE_SIZE: not___| work | raise serializers.ValidationError("File size too big!") | print("workkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk") |____ raise serializers.ValidationError("This type extension not allowed!!") else: return image class Meta: model = … -
Django static files aren't loading and runserver doesn't show 404s
I've got django admin working on my django website, but the static css files give 404s. I see this in the browsers network tab, but in the terminal where I run python manage.py runserver I see no output of any request being made whatsoever. This is what I see in the browser: So I suppose there's something wrong with my STATIC_URL or STATIC_ROOT: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') I ran python manage.py collectstatic, which created a bunch of nested folders containing static files. So I checked out the terminal output of the runserver command, expecting to see the 404s. But after I got the 404s in the browser I only see this in the terminal: $ ./manage.py runserver Performing system checks... System check identified no issues (0 silenced). March 03, 2021 - 20:19:44 Django version 3.0.11, using settings 'main.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. So at this point I'm lost as to how I can solve this. Why don't I see the requests in the terminal? The dev server is definitely working, because when I stop the dev server the site doesn't load at all anymore. Any help in how to debug this … -
django_avatar not displaying images in production
I'm using django-avatar to handle profile pictures uploaded by users for my django app. Works perfectly locally but the pictures are not displaying during production. On the backend I can see them being uploaded on cloudinary. Also each time i refresh the page, an extra copy of the avatar is uploaded on cloudinary. settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') DEFAULT_FILE_STORAGE='cloudinary_storage.storage.MediaCloudinaryStorage' AVATAR_CLEANUP_DELETED = True AVATAR_EXPOSE_USERNAMES = False AVATAR_AUTO_GENERATE_SIZES = [128] AVATAR_MAX_AVATARS_PER_USER = 1 AVATAR_GRAVATAR_BACKUP = False AVATAR_PROVIDERS = ( 'avatar.providers.PrimaryAvatarProvider', 'avatar.providers.DefaultAvatarProvider', ) In my template {% avatar user 128 class="rounded-circle" id="user_avatar" %} urls.py urlpatterns = [ url('avatar/', include('avatar.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How to prevent mySQL autoincrement from resetting in Django
I am creating a Django app where the primary keys are autoincrement fields. I need to use mySQL. I will need to export all the data to excel or perhaps another django app from time to time. Therefore the primary keys must be unique to be able to identify new records or records to be deleted in excel/other app. However, I have read that mySQL autoincrement counter resets to the max key when database restarts. This will result in reassignment of keys if the latest records were deleted. I need to avoid this. No key should be reassigned. How can this be done? -
Automatically create predefined objects in database for ManyToMany?
how would I go about automatically generating a list of objects in the database for DJango? Example model: #models.py class Book(models.Model): BOOKS = ( ('0','Secret Life of Bees'), ('1','Pride and Prejudice') ) name = models.CharField(max_length=100, choices=BOOKS) def __str__(self): return self.name class Library(models.Model): librarian = models.OneToOneField(UserProfile, on_delete=models.CASCADE, primary_key=True) books = models.ManyToManyField(Book) How would I automatically add all the books to the database so I don't have to manually add them using the admin control panel? -
Why does 'related_names' make my field required?
I am working with Django and Django rest_framework to create a simple API. I have 2 models: a Game model and a Rating model. The models are listed below class Game(models.Model): title = models.CharField(max_length=30) description = models.TextField(max_length=400) def numOfRatings(self): return len(Rating.objects.filter(game=self)) def avgRating(self): ratings = Rating.objects.filter(game=self) sum = 0 for rating in ratings: sum += rating.stars if len(ratings) > 0: return sum/len(ratings) else: return 0 # creating ratings for a movie class Rating(models.Model): game = models.ForeignKey(Game, on_delete=models.CASCADE, related_name='ratings') # rating for a specific game user = models.ForeignKey(User, on_delete=models.CASCADE) # user that the rating is tied too # user is imported from Django's user model stars = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)]) # making it so each user-movie combination can only have one entry in this model class Meta: unique_together = (('user','game')) index_together = (('user','game')) The rating model contains game as a foreign key. The issue is that when I try to create a game object via a post request, I get { "ratings": [ "This field is required." ] } Now, when I remove the related_name='ratings' everything is fixed and I can create Games through post requests. Why can't I create new Game objects without any ratings? ratings is not a field in … -
Django Foreign Key choices
I want to build an application in which a patient uploads his report to his companion doctor , So , I have two models one for Doctors and other for patients. What I want is to have a relationship between the two models , in which a patient chooses his doctor from the registered doctors. this is the code: class DoctorModel(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) doctorName = models.CharField(max_length = 150 , default="") doctorEmail = models.EmailField(max_length=50, default="") speciality = models.CharField(choices = SPECIALITY ,max_length = 20 , default="") doctorStatus = models.CharField(choices = DOCTOR_STATUS ,max_length = 15 , default="") class PatientModel(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) patientName = models.CharField(max_length = 150 , default="", editable=True) patientAge = models.IntegerField(default=0) patientEmail = models.EmailField(max_length=50, default="", editable=True) insuranceSyndicate = models.CharField(choices = INSURANCE_SYNDICATE, max_length = 15, default="") slug = models.SlugField(max_length = 50 , default= '') referencedDoctor = models.ForeignKey(DoctorModel, on_delete=models.Set_Null) What I want that when a patient choose the "referencedDoctor" , he choose him from "doctorName" in the DoctorModel How can I do it ? -
Correct Django Model Strategy for Relationships
I am in the middle of putting together a database that I can use on my home network that has contact information for friends and acquaintances. I am using Django 3 for this, and have three models that I would like to connect, but am having trouble figuring out how to wire it up the way to, to make it work like I think it should. I have two main storage models: Person and Offspring. The Person model contains all of the phone, email and other necessary contact information. The Offspring model only contains names and things like birthdays -- a model that is a trimmed down Person model, since kids don't need that much detail on them. I have a Household model that I have also put together that I want to fill with one or more Person models, and zero or more Offspring models. This contains information like house address and shared landline phone numbers, etc. In my Person model I have it set up like this: class Person(models.Model): # Omitted most model code household = models.ForeignKey(Household, related_name='persons', on_delete=models.CASCADE, blank=True, null=True, ) This works. And it would be fine for government work, but I would like to not … -
Using two Django models (auth_user and User) at the same time
First off, not really sure this is worth the effort, but I'm still curious. We migrated an old PHP application to Django and instead of using the auth_user table Django uses OOTB, we opted to use the AUTH_USER_MODEL = 'authentication.User' table the PHP application was using. I've tossed around the idea of migrating it to the Django default auth_user and extending it. I guess no good reason other than just using what Django provides OOTB, cleaning up a relatively minuscule amount of code and database tables. I'm curious: Is it possible for Django to have two AUTH_USER_MODEL so that both models are being written to until we are ready to pull the plug on the legacy User table? -
Failed - No file Downloading uploaded files in Django
I have a model here in Django in which an entity can have several uploaded files: from django.db import models from model_utils.models import TimeStampedModel from .managers import ProviderManager class Provider(TimeStampedModel): full_name = models.CharField('Nombre', max_length=100, unique=True) phone1 = models.CharField("Teléfono", max_length=50, blank=True, null=True) phone2 = models.CharField("Teléfono", max_length=50, blank=True, null=True) email1 = models.EmailField("Email", max_length=100, blank=True, null=True) email2 = models.EmailField("Email", max_length=100, blank=True, null=True) bank_info = models.TextField( "Info Banco", max_length=250, blank=True, null=True) objects = ProviderManager() class Meta: verbose_name = "Proveedor" verbose_name_plural = "Proveedores" ordering = ["full_name"] def __str__(self): return "Nombre: "+self.full_name def get_provider_files_names(self): provider_files = self.provider_files.all() file_list = [] for f in provider_files: # print(f.file.name.split('/')[-1]) file_list.append(f.file.name.split('/')[-1]) return file_list def get_provider_files_urls(self): provider_files = self.provider_files.all() file_list = [] for f in provider_files: file_list.append(f.file.url) return file_list class ProviderFiles(TimeStampedModel): file = models.FileField(upload_to="provider_files/%Y/%m/%d") provider = models.ForeignKey( Provider, on_delete=models.CASCADE, related_name='provider_files') class Meta: verbose_name = "Archivos Proveedor" verbose_name_plural = "Archivos Proveedores" def __str__(self): return "Nombre Proveedor: "+self.provider.full_name So then in my html I would like to access entity files and give the user links to download this files: <td> <a href="{{ provider.get_provider_files_urls.0 }}" download="{{ provider.get_provider_files_urls.0 }}"> Download File</a> </td> So then when download starts, it fails with error Failed - No file (file exists) Also important, if I access admin, and check … -
ValueError at /accounts/login/ The view accounts.views.signinView didn't return an HttpResponse object. It returned None instead
accounts/views.py : from django.shortcuts import render, redirect from .forms import CustomUserCreationForm from .models import CustomUser from django.contrib.auth.models import Group from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import login, authenticate, logout def signupView(request): if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') signup_user = CustomUser.objects.get(username=username) customer_group = Group.objects.get(name='Customer') customer_group.user_set.add(signup_user) else: form = CustomUserCreationForm() return render(request, 'signup.html', {'form':form}) def signinView(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect('phoneshop:allProdCat') else: return redirect('signup') else: form = AuthenticationForm() return render(request, 'signin.html', {'form': form}) def signoutView(request): logout(request) return redirect('signin') accounts/urls.py: from django.urls import path from phoneshop import views from .views import signupView, signinView, signoutView urlpatterns = [ path('create/', signupView, name='signup'), path('login/', signinView, name='signin'), path('logout/', signoutView, name='signout'), ] main/urls.py: from django.urls import path from . import views app_name ='phoneshop' urlpatterns = [ path('', views.allProdCat, name ='allProdCat'), path('<uuid:category_id>/', views.allProdCat, name='products_by_category'), path('<uuid:category_id>/<uuid:product_id>/', views.prod_detail, name='prod_detail'), ] I can't seem to figure out why the return value is None. I believe the issue to be in the urls somewhere as I have an issue with redirection. I have the same error when trying to logout as well. I … -
How to upload image to image kit using tinymce
Hey I am new to Django and want to integrate Django with tinymce for creating a blog I use pip install django-tinymce for installing tinymce. whenever I upload a image using tinymce it get stored in media file How can I upload it to the imagekit.io -
Static folder is not loading in my html template
Hello I am new to django in python I am working on a website and I am facing some errors while loading static files in my html template here are some of my codes: settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ImperfectCoder' ] STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static", ] urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='home'), path('about', views.about, name='about'), path('blog', views.blog, name='blog') ] tried to load the static by {% load static %} And implement it by <img src = "{% static'art-design-2.jpg' %}" alt = ""> The following error comes TemplateSyntaxError at /blog Invalid block tag on line 56: 'static'art-design-2.jpg''. Did you forget to register or load this tag? Another hint I got that in vs code I have installed django extension and when i load the static files it automaticlly shows what to write but this time it didin't please help me with this -
How to handle multiple daily deployments resetting Prometheus metrics
My team just started using Prometheus for monitoring our Django web application (django-prometheus). Like any common setup, metrics are published to a "/metrics" endpoint, which is scraped by Prometheus. Our problem is the fact that we deploy several times a day. On every deployment, the metrics are reset (all counters, gauges, etc. go back to zero) so we never have more than a few hours of metrics to review. I'd imagine this is a common problem with Prometheus. Is more than a few hours worth of aggregated metrics okay? Is there something I should do to persist metrics at any point in the pipeline? -
Using Django models with an already created DB table
I have a DB (lets call it data_db) containing some tables. I want to create a dashboard to present data from data_db, so I created a Django project for that purpose. When I want to get data from one of the tables in data_db, is there a way to do it with Models? (I want Django security management with the DB) or do I have to use raw SQL? One note: there is existing data in the data_db's table, and I don't want to create a new table with the same exact data on the default Django DB. I also use 2 DBs, Django default's and data_db and I created a database router for data_db to prevent Django from creating all its tables in there. Thanks. -
error on connecting oracle database in django
i am trying to connect my oracle 11g database to django but it didn't connect it show some error like return Database.connect( django.db.utils.DatabaseError: DPI-1047: Cannot locate a 32-bit Oracle Client library: "C:\oraclexe\app\oracle\product\11.2.0\server\bin\oci.dll is not the correct architecture". See https://cx-oracle.readthedocs.io/en/latest/user_guide/installation.html for help i sucessfully install 32 bit oracle client library but it still shows same error. i am new to django and this error pops up when i use command python manage.py makemigrations it didn't create migration instead it shows this error. it would be pleasure if someone helps me. thankyou :) -
Config Apache WSGI and Django always getting `There was an error while handling your request.` - Apache
I'm trying to serve a Django app (helios) with Apache2, but I'm always receiving this "There was an error while handling your request. when trying to access the server. The server have the following naming debian.serverdomain and I tried to access using http://debian.serverdomain ,http://debian.serverdomain:80 and http://<hostname ip>:80, but didn't work. The apache configuration didn't show errors and the wsgi appears on the apache status. The apache conf: helios.conf Alias /favicon.ico /var/www/helios-server/sitestatic/favicon.ico AliasMatch ^/([^/]*\.css) /var/www/helios-server/static/styles/$1 Alias /media /var/www/helios-server/sitestatic Alias /static /var/www/helios-server/sitestatic Alias /booth /var/www/helios-server/sitestatic/booth Alias /verifier /var/www/helios-server/sitestatic/verifier <VirtualHost *:80> DocumentRoot /var/www/helios-server <Directory /var/www/helios-server> Options All AllowOverride All Require all granted </Directory> <Directory /var/www/helios-server/static> Options All AllowOverride All Require all granted </Directory> <Directory /var/www/helios-server/media> Options All AllowOverride All Require all granted </Directory> <Directory /var/www/helios-server> Options All AllowOverride All Require all granted <Files wsgi.py> Order deny,allow Allow from all Require all granted </Files> </Directory> ErrorLog /var/www/helios-server/apache.error.log CustomLog /var/www/helios-server/access.log combined </VirtualHost> WSGIApplicationGroup %{GLOBAL} WSGIDaemonProcess helios-server display-name=%{GROUP} python-home=/var/www/helios-server/.venv python-path=/var/www/helios-server:/.venv/lib/python2.7:/.venv/lib/python2.7/site-packages WSGIProcessGroup helios-server WSGIScriptAlias / /var/www/helios-server/wsgi.py The 'deploy' bash script: #!/bin/bash if [[ `uname` == 'Linux' ]]; then cp /var/www/helios-server/deploy/apache/helios.conf /etc/apache2/sites-available sudo apachectl configtest sudo chmod 644 wsgi.py sudo a2enmod rewrite sudo a2dissite 000-default.conf sudo a2ensite helios.conf sudo a2enmod wsgi sudo systemctl reload apache2 sudo chown www-data … -
Cant sign into my Django project but i can sign up no problem
Hey guys I'm just getting an error thrown up at me when I go to sign in on my Django project I was just wondering could anyone help shed some light as to what the error is. Ill include both my views and URLs below. I assume this is where the error must be but I'm unsure so apologies if I have not provided the right code. I will also include my templates. Repost urls from django.urls import path from phoneshop import views from .views import signupView, signinView, signoutView urlpatterns = [ path('create/', signupView, name='signup'), path('login/', signinView, name='signin'), path('logout/', signoutView, name='signout'), ] views from django.shortcuts import render, redirect from .forms import CustomUserCreationForm from .models import CustomUser from django.contrib.auth.models import Group from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import login, authenticate, logout def signupView(request): if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') signup_user = CustomUser.objects.get(username=username) customer_group = Group.objects.get(name='Customer') customer_group.user_set.add(signup_user) else: form = CustomUserCreationForm() return render(request, 'signup.html', {'form':form}) def signinView(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect('phoneshop:allProdCat') else: return redirect('signup') else: form = AuthenticationForm() return render(request, 'signin.html', … -
Can connect using domain name through SSH, but not through browser
I am making a backend website for myself hosting through DigitalOcean and have bought a domain name through NameCheap. This is a bit more of a personal site, so I am going to use psuedonames to keep the question general. All I am trying to do is deploy a Django website on the server using Gunicorn and Nginx. I have followed a couple of tutorials that have helped me get to where I am now. The issue I am having is that if I specify hostname in my nginx file without my Server IP Address, I am unable to connect to my server through a browser. However, if I do specify the Server IP Address, I will be able to connect to the server through the IP. I do also have port 22 open so that I may SSH into the server, and when I use SSH, I can successfully use the domain name (e.g. ssh username@hostname rather than ssh username@server_IP_address). From what I can infer, NameCheap is connecting my domain name to the DigitalOcean servers, so this makes me think I am missing a line of code or something separating me from using the IP address rather than my … -
django, mypy : queryset, choices. error: Incompatible types
We have: In models.py class Language(models.IntegerChoices): en = 1 ru = 2 class Translation(models.Model): language_id = models.PositiveIntegerField(choices=Language.choices) mnemonic = models.CharField(max_length=255) translation = models.CharField(max_length=255) in serializers.py 66 def get_translations(self, obj): 67 language: int = self.initial_data.get('language') or settings.SERVER['current_language_id'] 68 common_public = Translation.objects.filter(language_id=language).exclude(mnemonic__startswith='dictionary') When i check it by mypy: resources/serializers.py:67: error: Incompatible types in assignment (expression has type "Union[Any, object]", variable has type "int") if in serializers.py 66 def get_translations(self, obj): 67 language: Union[Any, object] = self.initial_data.get('language') or settings.SERVER['current_language_id'] 68 common_public = Translation.objects.filter(language_id=language).exclude(mnemonic__startswith='dictionary') Check it by mypy: resources/serializers.py:68: error: Incompatible type for lookup 'language_id': (got "Union[Any, object]", expected "Union[str, int]") 3) 66 def get_translations(self, obj): 67 language: Union[str, int] = self.initial_data.get('language') or settings.SERVER['current_language_id'] 68 common_public = Translation.objects.filter(language_id=language).exclude(mnemonic__startswith='dictionary') Check it: resources/serializers.py:67: error: Incompatible types in assignment (expression has type "Union[Any, object]", variable has type "Union[str, int]") What`s wrong? mypy.ini: [mypy] python_version = 3.8 mypy_path = ./stubs check_untyped_defs = True disallow_any_generics = True disallow_untyped_calls = True disallow_untyped_decorators = True ignore_errors = False ignore_missing_imports = True implicit_reexport = False strict_optional = True strict_equality = True no_implicit_optional = True warn_unused_ignores = True warn_redundant_casts = True warn_unused_configs = True warn_unreachable = True warn_no_return = True plugins = mypy_django_plugin.main [mypy.plugins.django-stubs] django_settings_module = server.settings [mypy-*.migrations.*] ignore_errors = True -
Dynamically set choices in django?
How can I allow a user to dynamically set the status of a record? I don't want to set the statuses in place and the model needs to be able to work across many models, such as "CampaignStatus", etc. class Status(models.Model): title = models.CharField(max_length=50, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return '%s' % (self.title) def choices(self): queryset = list(Status.objects.filter(task=self)) return queryset class Task(models.Model): status = models.IntegerField(choices=choices) class TaskStatus(Status): task = models.ForeignKey(Task, on_delete=models.CASCADE) This gives me the error: 'choices' must be an iterable (e.g., a list or tuple). How can I filter through the Status models to only have choices that are related to the TaskStatus? As a quick example, something like this but that would allow for me to filter only related objects: class Status(models.Model): title = models.CharField(max_length=50, blank=True) class Task(models.Model): status = models.ForeignKey(Status, on_delete=models.CASCADE, related_name='currentstatus') class TaskStatus(Status): task = models.ForeignKey(Task, on_delete=models.CASCADE)