Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reverse query clash
I am trying to make a chat system where a user can create a chat and become the owner of the said chat and the chat can have other users inside. class UserProfile(models.Model): #username = models.CharField(max_length=30, unique=True, default=User.username)# django creates username automatically? user = models.OneToOneField(DjangoUser, on_delete=models.CASCADE) display_name = models.CharField(max_length=50) picture = models.ImageField(upload_to = 'profile_images', blank=True) def __str__(self): return self.user.username Thats my user model class Chat(models.Model): name = models.CharField(max_length=50, unique=True) description = models.CharField(max_length=240) users = models.ManyToManyField(UserProfile) owner = models.OneToOneField(UserProfile, on_delete = models.CASCADE) def __str__(self): return self.name Thats the chat model -
The error " Could not parse the remainder: '=' from '=' "
This error is displayed in the line <form action="{% url "make_order" product_id=product.id %}" method-="POST"> I do not know how to fix it, because everything seems right I hope you can help me {% extends "core/base_layout.html" %} {% load static %} {% block meta %} <link rel="stylesheet" href="{%static 'styles/make_order.css'%}"> {% endblock %} {% block content %} <form action="{% url "make_order" product_id=product.id %}" method-="POST"> {{ error }} {% for input in form %} <div> <label for="{{ input.id_for_label }}"> {{input.label}}</label> </div> {{ input }} <p> {{ input.errors }} </p> {% endfor %} </form> {% endblock %} -
Django Filterset object is not callable
I'm trying to use a custom filterset class with DjangoFilterBackend to filter my products by some details that are different based on their category, but I get the error "'ProductFilter' object is not callable". My filtering works fine when I don't limit the choices based on chosen category, but when I try limitting them I get the above error. these are my models: class Category(models.Model): title = models.CharField(max_length=50) desc = models.TextField(default='', blank=True) slug = models.SlugField() class ProductEnumProperty(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='product_enum_properties') name = models.CharField(max_length=20) def __str__(self): return self.name class ProductPropertyState(models.Model): property = models.ForeignKey(ProductEnumProperty, on_delete=models.CASCADE, related_name='product_property_states') state = models.CharField(max_length=20) def __str__(self): return f'{self.property.name} - {self.state}' class Product(models.Model): title = models.CharField(max_length=50) slug = models.SlugField() category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name='products') desc = models.TextField(blank=True, null=True) price = models.DecimalField(max_digits=6, decimal_places=2) date_created = models.DateTimeField(auto_now_add=True) props = models.ManyToManyField(ProductPropertyState, ) For example: Category: jeans---------->ProductEnumProperty:flyer type----------->(ProductPropertyStates:(1-buttons 2-zipper)) filters.py: class ProductFilter(FilterSet): class Meta: model = Product fields = { 'price': ['gt', 'lt'], 'props': ['exact'], } def __init__(self, *args, **kwargs): category_slug = kwargs['category_slug'] del kwargs['category_slug'] super(ProductFilter, self).__init__() self.filters['props'].extra.update( {'queryset': ProductPropertyState.objects.filter(property__category__slug=category_slug)}) views.py: class ProductByCategory(ListAPIView): def get_category(self): category_slug = self.kwargs.get('category_slug') return category_slug serializer_class = ProductMiniSerializer filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter] filterset_class = ProductFilter(category_slug=get_category) search_fields = ['title', 'desc', 'category__title'] ordering_fields = ['price', … -
Django RichTextUploadingField in ckeditor related issue
I am facing a problem in RichtextEditor when I used RichTextUploadingField is field in model then I add data to admin panel and after calling by api it is showing this image after api call but the problem is frontend developer can't use it to show this image. Is there any problem in my code? ` INSTALLED_APPS = [ 'ckeditor', 'ckeditor_uploader', ] CKEDITOR_UPLOAD_PATH = "uploads/" STATIC_URL = '/static/' STATICFILES_DIRS = [STATIC_DIR, ] Media MEDIA_ROOT = MEDIA_DIR MEDIA_URL = '/media/' ` when add data through admin panel in rich text editor rich text editor look like this from postman "body_with_image": "<p><img alt=\"\" src=\"/media/uploads/2023/02/25/mountains-3840x2160.jpg\" style=\"height:2160px; width:3840px\" /></p>" Is there any correction needed in my code -
How to change Django default date format
I want to change the default Django date format from year-day-month to day-month-year format I tried adding DATE_INPUT_FORMATS=[‘%d.%m.%Y] in settings.Py file but the changes still doesn’t reflect while using the form -
Django. POST request after reloading a page. Sign up form
When user enters incorrect data in form, he gets errors. If after that user reloads a page, he gets the same page, the same form with the same fields, errors. I don't know why after reloading a page request is POST. Every time after sending form, when I reload page with form I send a POST request. views.py from django.shortcuts import render from django.shortcuts import render, redirect from .forms import LogInForm, SignUpForm from django.contrib.auth.decorators import login_required, permission_required from django.contrib.auth.hashers import make_password from django.contrib.auth import authenticate, logout, login as auth_login from django.contrib import messages import os import shutil # Create your views here. @login_required def index(request): return render(request, 'index.html') def login(request): logInForm = LogInForm() if request.method == 'POST': form = LogInForm(request.POST) if form.is_valid(): cd = form.cleaned_data user = authenticate( username=cd['username'], password=cd['password']) if user is not None: auth_login(request, user) return redirect("main") else: messages.error(request, "Invalid login or password") return redirect('login') else: form = LogInForm() else: return render(request, 'logIn.html', {"form": logInForm}) def signUp(request): def createFolder(username): toFolder = "jsons/" + username fromFolder = "scripts/" os.mkdir(toFolder) toFolder = "jsons/" + username + '/scripts' os.mkdir(toFolder) os.mkdir("jsons/" + username + "/messages") if (os.path.exists(fromFolder) and os.path.exists(toFolder)): for file in os.listdir(fromFolder): if os.path.isfile(os.path.join(fromFolder, file)): shutil.copy(os.path.join(fromFolder, file), os.path.join(toFolder, file)) if os.path.isdir(os.path.join(fromFolder, … -
can't multiply sequence by non-int of type 'decimal.Decimal'
I have a cart in my project which was working fine but I don't know what happened that now when adding an item to my cart this error keeps coming up: TypeError at /cart/ can't multiply sequence by non-int of type 'decimal.Decimal' this is my form: class AddToCartProductForm(forms.Form): QUANTITY_CHOICES=[(i,str(i)) for i in range(1,30)] quantity=forms.TypedChoiceField(choices=QUANTITY_CHOICES,coerce=int) inplace=forms.BooleanField(required=False,widget=forms.HiddenInput) this is my add function in card class: def add(self,post,quantity=1,replace_current_quantity=False): post_id=str(post.id) if post_id not in self.cart: self.cart[post_id]={'quantity':quantity} if replace_current_quantity: self.cart[post_id]['quantity']=quantity else: self.cart[post_id]['quantity']+=quantity self.save() and this is my view: def add_to_cart_view(request,post_id): cart=Cart(request) post=get_object_or_404(Posts,id=post_id) form=AddToCartProductForm(request.POST) if form.is_valid(): cleaned_data=form.cleaned_data quantity=cleaned_data['quantity'] cart.add(post,quantity,replace_current_quantity=cleaned_data['inplace']) else: print(form.errors.as_data()) return redirect('cart:cart_detail') I tried giving the quantity a default int value in case it is null but didn't work. -
Adding simple cart item in Cart in Django
Being completely new to Django, I want to add simple cart item in Django. And also want to retrieve this cart items in Get request. What I will send in POST request is: {"item":"itemName","price":"100"} This should get stored for the current user. And when I make GET request, I want JSON array containing all previously stored items. [{"item":"itemName1","price":"100"}, {"item":"itemName2","price":"200"}, {"item":"itemName3","price":"300"}] If anyone can put very simple code in terms of views and models, that would be very helpful. In examples on stackoverflow, I saw multiple posts. Some use complex Product object, some use .html forms etc. But I need to store simple objects and get these objects as JSON. Any working code help? -
Error when re-entering a Django web application
In a web application, I get a CSRF-Token error when logging back in after the user logs out. Of course, this problem only occurs when working with a smart phone. I put the {%CSRF-TOKEN%} tag in the designed login form, but this error occurs only on smartphones and after logging out and when logging in again. -
How to add text AFTER inputs in Django forms
I have a form which ideally would render like this: <label>Price: </label> <input type="number" />USD Visually it would be Price: |___________| USD I know that the label attribute of a form field can add text BEFORE an input, but I want to know if it's possible to add text AFTER an input. (1) I understand if I iterate over fields in the template, I would be able to achieve this with something like {{ field }} {% if field.name == "price" %} &nbsp;USD {% endif %} However I do not want to go this route if possible. (2) I already tried help_text, but it adds an extra <br /> tag between the input and the help text, and it does not render what I want. <label>Price: </label> <input type="number" /> <br /> <span>USD</span> Price: |___________| USD -
How to display only subscribed posts in Python
So there is 2 apps in Python, one is for blog posts and second is for user profile. I want to display on my HTML main page only user's subscribed posts. blog post models.py class News(models.Model): user = models.ForeignKey( User, related_name='user_news', on_delete=models.CASCADE ) title = models.CharField( max_length=250 ) description = RichTextField() def __str__(self) -> str: return self.title def save(self, *args, **kwargs): updating = self.pk is not None blog post views.py def home(request): blogs= Blog.objects.order_by('-created_date') users = User.objects.order_by('-date_joined') context = { "blogs": blogs, 'users': users, } return render(request, 'home.html', context) user profile models.py class User(AbstractUser): followers = models.ManyToManyField("Follow") def __str__(self): return self.username class Follow(models.Model): followed = models.ForeignKey( User, related_name='user_followers', on_delete=models.CASCADE ) followed_by = models.ForeignKey( User, related_name='user_follows', on_delete=models.CASCADE ) def __str__(self) -> str: return f"{self.followed_by.username} started following {self.followed.username}" user profile views.py def follow_or_unfollow_user(request, user_id): followed = get_object_or_404(User, id=user_id) followed_by = get_object_or_404(User, id=request.user.id) follow, created = Follow.objects.get_or_create( followed=followed, followed_by=followed_by ) if created: followed.followers.add(follow) else: followed.followers.remove(follow) follow.delete() return redirect("view_user_information", username=followed.username) what i did and it did not show posts of subscribed accounts <div class="swiper-wrapper"> {% for blog in account.user_blogs.all %} {% for blog in blogs|slice:"2" %} <div class="swiper-slide subscription-card" > <a href="{% url 'news_details' new.slug %}"> <div class="subscription-card__header"> <div> <h5>{{blog.user.first_name}} {{blog.user.last_name}}</h5> <span>{{blog.created_date}}</span> </div> </div> … -
pipenv install django=~3.1.0 command giving error
Installing django=~3.1.0... Resolving django=~3.1.0... Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pipenv/patched/pip/_vendor/packaging/requirements.py", line 102, in __init__ req = REQUIREMENT.parseString(requirement_string) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pipenv/patched/pip/_vendor/pyparsing/core.py", line 1141, in parse_string raise exc.with_traceback(None) pipenv.patched.pip._vendor.pyparsing.exceptions.ParseException: Expected string_end, found '=' (at char 6), (line:1, col:7) I am getting above error in command line of mac for pipenv install django=~3.1.0 -
I want to send and an otp with REST Framework
self._otp = str(randint(100000, 999999)) AttributeError: 'str' object has no attribute '_otp' [25/Feb/2023 14:04:01] "POST /login1/ HTTP/1.1" 500 101590 class OTPGenerator: def init(self, phone_number): self.phone_number = phone_number self._otp = None def generate_otp(self): self._otp = str(randint(100000, 999999)) redis_conf.set(name=self.phone_number, value=self._otp, ex=30) otp_code = redis_conf.get('phone_number') return otp_code def __str__(self): return self.otp def send(self): send_sms(phone_number=self.phone_number, otp=self.otp) def value(self): return redis_conf.get(self.phone_number) def is_valid(self, otp): if redis_conf.get(self.phone_number) == otp: redis_conf.delete(self.phone_number) return True return False -
Apache2 using incorrect Python location
I'm using Apache2 with mod_wsgi to server a Django app, and from the error log I can tell that for some reason it's trying to use the system python library instead of the venv one. I have PYTHONPATH set to the venv (venv/lib/python3.8) and mod-wsgi built specifically for Py3.8 so that shouldn't be an issue, and in my Virtual Host file I have python home set to the venv's folder. Error: [wsgi:error] from . import ccompiler [wsgi:error] File "/var/www/djangoenv/lib/python3.8/site-packages/numpy/distutils/ccompiler.py", line 8, in <module> [wsgi:error] from distutils import ccompiler [wsgi:error] ImportError: cannot import name 'ccompiler' from 'distutils' (/usr/lib/python3.8/distutils/__init__.py) It is referring to many packages in the correct location, being the virtual environment, but in the end it seems to defer to the system Python for some reason and fails. -
Removing objects from a queryset by ID optimal implementation
I have a queryset of 1000000 objects MyModel. All objects in queryset have an ID. I pass a list of ids to remove, for example: ids = ['1', '23', '117', ...] # len = 100000 Then, i need to delete objects in queryset with ids. What is the best way to do it? My variant: for id in ids: obj = MyModel.objects.filter(pk=id) obj.delete() I'm not sure about it, because it will make a 100000 queries to the database, maybe it makes sense to convert the queryset to a list, then filter it by id? On the other hand, if there are a million objects in the database, and only one needs to be deleted, this will create an inverse relationship. -
Django: AutoFields must set primary_key=True
After doing a python manage.py inspectdb on my already existing PostgreSQL database, and generating the models, I'm getting this error when I want to migrate: app.PatientHasPhysicallocalization.id: (fields.E100) AutoFields must set primary_key=True. Here is my generated model: class PatientHasPhysicallocalization(models.Model): id = models.BigAutoField() uid = models.CharField(max_length=155) patientid = models.ForeignKey(Patient, models.DO_NOTHING, db_column='patientid', primary_key=True) physicallocalizationid = models.ForeignKey('Physicallocalization', models.DO_NOTHING, db_column='physicallocalizationid') creationdate = models.DateField() creatorname = models.CharField(max_length=45) isactive = models.IntegerField() class Meta: managed = False db_table = 'patient_has_physicallocalization' unique_together = (('patientid', 'physicallocalizationid'),) I don't want to modify my database table -
htmx:targeterror in django project
My objective is to click on a list item (an asset) to load and update a form, that is right next to the list, using htmx in django, but I am getting HTMX:Targeterror.. I believe I have given the hx-target correctly, I cannot figure out why this problem appears.. Someone, please help.. I am getting htmx:targetError when using the below code.. can u help me figure out the issue? TEMPLATE {% for asset in portfolio.children %} <tr id="asset-{{ asset.id }}" > <td class="col-md-12 col-lg-12 node-style" hx-get="{% url 'portfolio:asset-update' asset.id %}" hx-target="#assetUpdate" hx-swap="outerHTML">&emsp;{{ asset.name }}</td> </tr> VIEWS.PY ASSET_UPDATE def asset_update(request, id): asset = Asset.objects.get(id=id) update_asset_form = AssetForm(request.POST or None, instance=asset) if update_asset_form.is_valid(): update_asset_form.save() context = { "update_asset_form": update_asset_form, "asset": asset, } return render(request, "portfolio/partials/02-asset-update.html", context) 02-ASSET-UPDATE.HTML {% load crispy_forms_filters %} {% load crispy_forms_tags %} <div id="assetUpdate"> <form method="post" class="form-group" novalidate> {% csrf_token %} {% crispy update_asset_form %} <button type="submit" class="bland-button-style" hx-post="{% url 'portfolio:asset-update' asset_id=asset.id %}" hx-target="#assetUpdate" hx-swap="outerHTML"> <i class="fa-solid fa-cloud-arrow-down fa-lg header-icon-style portfolio-save-icon"></i> </button> </form> </div> -
can't able to host api using my mobile hotspot ipaddress in python?
app = Flask(__name__) app.run(host='192.168.184.101',debug=True,port=8000) app.config.from_pyfile('customerdbconfigure.py') and also i have included this ip in settings.py ALLOWED_HOSTS = ['192.168.184.101'] also tried running python manage.py runserver 192.168.184.101:8000 in cmd But its showing like this if anyone know about this help me. -
Django 4: How to modify MultiPolygonField from nullable to not-null
I am trying to convert my MultiPolygonField field from this: multipolygon = MultiPolygonField(null=True) to this: multipolygon = MultiPolygonField(null=False) It looks simple, so I execute "makemigrations" and I get the usual message warning that the database needs something to populate existing rows (I confirmed that there is no row in my database with that field being null): Whether I choose option 1: Provide a one-off default now (will be set on all existing rows with a null value for this column) And set the following as default: 'SRID=3857;POINT(0.0 0.0)' or option 2: Ignore for now. Existing rows that contain NULL values will have to be handled manually, for example with a RunPython or RunSQL operation I get the following error when I execute "migrate": ValueError: Cannot alter field borders.Border.multipolygon into borders.Border.multipolygon - they do not properly define db_type (are you using a badly-written custom field?) I have been able to make that same change with other simpler field types without any issue. How to do this with MultiPolygonFields? I am using Django 4 and sqlite 3.31, in case that matters. -
Django - authenticate() returning None even if user exists in database and the credentials are correct
authenticate() returns None for credentials even if the user exists in the database and the credentials are correct. The function for registration, register(): def register(request): registered = False ctx = {} if request.method == 'POST': username = request.POST.get("username") full_name = request.POST.get("fullname") password = request.POST.get("password") email = request.POST.get("email") if len(User.objects.filter(username=username)) == 0: ctx["username_exists"] = False user_form = UserForm(data=request.POST) if user_form.is_valid(): user = User.objects.create_user(username, email, password) user.save() user_profile = UserProfile(user=user, full_name=full_name, email_id=email) user_profile.save() if user: if user.is_active: login(request,user) return HttpResponseRedirect(reverse('index')) else: return HttpResponse("Your account was inactive.") else: print("Someone tried to login and failed.") print("They used username: {} and password: {}".format(username,password)) return HttpResponse("Invalid login details given") else: return HttpResponse("Contains @") else: ctx["username_exists"] = True return render(request,'main/register.html', ctx) elif request.method == "GET": form = User() ctx["form"] = form return render(request,'main/register.html', ctx) Looking at the admin, I can see the user exists. The following proves it exists in the database: >>> from django.contrib.auth.models import User >>> user = User.objects.get(username='<username>') >>> print(user) <username> This is what I'm doing - python3 manage.py shell >>> from django.contrib.auth import authenticate >>> user = authenticate(username="<username>", password="<password>") >>> print(user) None This hasn't ever occurred to me before and I don't know what to do. Help? -
how to create virtual environment files in the project's directory
i want the pipenv to create the pipfile and .lock file in my project directory . there are suggestions to export PIPENV_EVNV_IN_PROJECT=1 but i dont know where this variable is and how to export them. and can i simply copy the pipfiles to my projects directory ? -
Method Not Allowed (GET): /cart/add/1/
I have a problem with allow method GET in my project, I find out problem but nothing working. I try everything, but nothing working, the messages in my postman is {Method Not Allowed (GET): /cart/add/1/} Please help me how to solve this problem? cart/view @require_POST def cart_add(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartAddProductForm(request.POST) print('privet') if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update']) return redirect('cart:cart_detail') def cart_detail(request): cart = Cart(request) for item in cart: item['update_quantity_form'] = CartAddProductForm(initial={'quantity': item['quantity'], 'update': True}) return render(request, 'cart/detail.html', {'cart': cart}) cart/url path('', cart_detail, name='cart_detail'), path('add/<int:product_id>/', cart_add, name='cart_add'), path('remove/<int:product_id>/', cart_remove, name='cart_remove') shop/view def product_detail(request, id, slug): product = Product.objects.filter(id=id, slug=slug) cart_product_form = CartAddProductForm() return render(request, 'web/catalog.html', {'product': product, 'cart_product_form': cart_product_form}) shop/detail.html <form action="{% url 'cart:cart_add' product.id %}" method="post"> {% csrf_token %} {{ cart_product_form.as_p }} {{ cart_product_form.non_field_errors }} <div class="Card-hover"> <a class="Card-btn" href="{% url 'cart:cart_add' product.id %}" type="submit" value='add to cart'><img src="{% static 'img/icons/card/cart.svg' %}" alt="cart.svg"/></a> </div> </form> -
how can i dynamically generate divs in my HTML template after a form submission, when working with django?
I am building a MCQs Bank using django, I have created all the front end files for my project, I have created django project, i have written some functons in views as well and created some of the models as well, I haven't created any forms yet, i have design a page which contains a button on which the user click and it redirects to a page where I created a form with the help of which user can enter the new course details which he want to add. Now on the redirected page when user done filling the details about course and click on add course I want to return the user to previous page where he can see all the courses he added and the new course must be display there as well. i want to make a div in which I want to place divs of all courses. I dont want to display anything in that div untill the user enter a new course, now when the user add a new course it should be display in that div of containing all course in the form of a div, now everytime the user enter a new course … -
Django form.save() does not update database
I have a Django User model with a background and a profile picture, what I want to do is give the user the ability to submit a new background photo/picture and have it saved to the database. The way I have done this is like this settings.html: {% extends 'main.html' %} {% block content %} <form action="" method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" name="user-settings-save" value="submit"> </form> {% endblock content %} forms.py class UserProfileForm(ModelForm): class Meta: model = User fields = ['avatar', 'background'] models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(blank=True, default='', unique=True) password = models.CharField(max_length=50) name = models.CharField(max_length=255, default='', unique=True) avatar = models.ImageField(default='default.png', upload_to ='uploads/') background = models.ImageField(default='default.png', upload_to ='uploads/') score = models.IntegerField(default=1) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_verified = models.BooleanField(default=False) register = models.CharField(max_length=255, default='') objects = CustomUserManager() USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['name'] def __str__(self): return self.name views.py def userSettings(request): form = UserProfileForm(instance=request.user) if request.method == 'POST': if 'user-settings-save' in request.POST: form = UserProfileForm(request.POST, request.FILES, instance=request.user) if form.is_valid(): if backendActionAuth(request, 'user-settings-save', form): form.save() return redirect('user-profile', request.user.id) context = {'form': form} return render(request, 'base/settings.html', context) and urls.py urlpatterns = [ path('', views.home, name="home"), path('post/<str:pk>/', views.post, name="post"), path('browse/<str:tk>/', views.browse, name="browse"), path('register/', views.register_user, … -
How to randomize key objects in model form and successfully submit in Django
I am trying to save user response (choice) in my Django application out of a set of values in the source model. The user is expected to select one of the many choices presented on the form (as radio buttons). The source model looks like this: class Emotion(models.Model): emote_id = models.AutoField(primary_key=True, ...) emote_state_grp = models.ForeignKey(EmotGroup, ...) # Grouping of Emotion State emote_state = models.CharField(max_length=55, ...) The response/s will be saved in the following model: class EmoteStateResponse(models.Model): emote_state_test = models.AutoField(primary_key=True, ...) emote_state_selected = models.ForeignKey(Emotion, ...) Using a model form I am able to successfully save user choice (i.e. the "emote_state" value) in table "EmoteStateResponse". However, as the choices might run into a number of instances of field "emote_state" (individual emotions) of table "Emotion", I am trying to select "at random" only a minimal number to display. To do that, I am trying to randomize the choices in my form that goes like the following: import random class EmoteTestForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(EmoteTestForm, self).__init__(*args, **kwargs) self.auto_id = True class Meta: model = EmoteStateResponse # ... fields = ('emote_state_selected', ...) def __init__(self, *args, **kwargs): super(EmoteTestForm, self).__init__(*args, **kwargs) qs_emot_state = Emotion.objects.all().values_list('emot_state_grp__emotion_grp_id', 'emote_id') # "emotion_grp_id": Key Field model "EmotGroup" list_qs_emot_state = list(qs_emot_state) rand_emot_state_list = …