B
B
Bjornie2017-03-21 05:32:03
Django
Bjornie, 2017-03-21 05:32:03

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()
    )

Now it returns me:
<option value="(1, &#39;Вася)">(1, &#39;Вася)</option>
<option value="(2, &#39;Петя)">(2, &#39;Петя)</option>

And puts them both in option=value and in its name.
Before that, I struggled with the queryset and the default empty_label, but it seems to work now, and I want to understand how to put the tuple in its place
<option value="1">Вася</option>
<option value="2">Петя</option>

In the template, I immediately display the form {{ form }}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Igor Che, 2017-03-21
@chewarer

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 question

Ask a Question

731 491 924 answers to any question