Answer the question
In order to leave comments, you need to log in
How to pass tuple elements to ModelChoiceField?
I've been struggling with this for two hours now and I don't understand how to pass the list to the form, so that id is the option value, and name is the name of the item in the drop-down menu.
forms.py code:
from django import forms
from .models import Names
class SearchNamesForm(forms.Form):
def __init__(self, *args, **kwargs):
super(SearchNamesForm, self).__init__(*args, **kwargs)
self.fields['selectName'].empty_label = "..."
self.fields['selectName'].widget.attrs['class'] = 'searchform-main__select'
self.fields['selectName'].queryset = Names.objects.all().values_list('id', 'name')
selectName = forms.ModelChoiceField(
required=False,
widget=forms.Select,
queryset=Names.objects.none()
)
<option value="(1, 'Вася)">(1, 'Вася)</option>
<option value="(2, 'Петя)">(2, 'Петя)</option>
<option value="1">Вася</option>
<option value="2">Петя</option>
Answer the question
In order to leave comments, you need to log in
Yesterday I had exactly the same problem.
from django import forms
from models import sentry_user
# переопределяем класс
class MyChoice(forms.ModelChoiceField):
def label_from_instance(self, obj):
return obj.full_name # Название поля которое нужно отображать в списке
# собственно форма
class Myform(forms.ModelForm):
worker = MyChoice(
queryset=sentry_user.objects.filter(is_active=1).all(),
empty_label='Все',
widget=forms.Select(attrs={'class': 'dropdown'}), required=False, label='Сотрудник')
class Meta:
model = sentry_user
fields = ('worker')
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question