field choices() as queryset?

30.7k Views Asked by At

I need to make a form, which have 1 select and 1 text input. Select must be taken from database. model looks like this:

class Province(models.Model):
    name = models.CharField(max_length=30)
    slug = models.SlugField(max_length=30)

    def __unicode__(self):
        return self.name

It's rows to this are added only by admin, but all users can see it in forms. I want to make a ModelForm from that. I made something like this:

class ProvinceForm(ModelForm):
    class Meta:
        CHOICES = Province.objects.all()

        model = Province
        fields = ('name',)
        widgets = {
            'name': Select(choices=CHOICES),
        }

but it doesn't work. The select tag is not displayed in html. What did I wrong?

UPDATE:

This solution works as I wanto it to work:

class ProvinceForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(ProvinceForm, self).__init__(*args, **kwargs)
        user_provinces = UserProvince.objects.select_related().filter(user__exact=self.instance.id).values_list('province')
        self.fields['name'].queryset = Province.objects.exclude(id__in=user_provinces).only('id', 'name')

    name = forms.ModelChoiceField(queryset=None, empty_label=None)

    class Meta:
        model = Province
        fields = ('name',)
4

There are 4 best solutions below

1
On

ModelForm covers all your needs (Also check the Conversion List)

Model:

class UserProvince(models.Model):
    user = models.ForeignKey(User)
    province = models.ForeignKey(Province)

Form:

class ProvinceForm(ModelForm):
    class Meta:
        model = UserProvince
        fields = ('province',)

View:

   if request.POST:
        form = ProvinceForm(request.POST)
        if form.is_valid():
            obj = form.save(commit=True)
            obj.user = request.user
            obj.save()
   else:
        form = ProvinceForm() 
7
On

Read Maersu's answer for the method that just "works".

If you want to customize, know that choices takes a list of tuples, ie (('val','display_val'), (...), ...)

Choices doc:

An iterable (e.g., a list or tuple) of 2-tuples to use as choices for this field.

from django.forms.widgets import Select


class ProvinceForm(ModelForm):
    class Meta:
        CHOICES = Province.objects.all()

        model = Province
        fields = ('name',)
        widgets = {
            'name': Select(choices=( (x.id, x.name) for x in CHOICES )),
        }
0
On

the two solutions given by maersu and Yuji 'Tomita' Tomita perfectly works, but there are cases when one cannot use ModelForm (django3 link), ie the form needs sources from several models / is a subclass of a ModelForm class and one want to add an extra field with choices from another model, etc.

ChoiceField is to my point of view a more generic way to answer the need.

The example below provides two choice fields from two models and a blank choice for each :

class MixedForm(forms.Form):
    speaker = forms.ChoiceField(choices=([['','-'*10]]+[[x.id, x.__str__()] for x in Speakers.objects.all()]))
    event = forms.ChoiceField(choices=( [['','-'*10]]+[[x.id, x.__str__()] for x in Events.objects.all()]))

If one does not need a blank field, or one does not need to use a function for the choice label but the model fields or a property it can be a bit more elegant, as eugene suggested :

class MixedForm(forms.Form):
    speaker = forms.ChoiceField(choices=((x.id, x.__str__()) for x in Speakers.objects.all()))
    event = forms.ChoiceField(choices=(Events.objects.values_list('id', 'name')))

using values_list() and a blank field :

    event = forms.ChoiceField(choices=([['','-------------']] + list(Events.objects.values_list('id', 'name'))))

as a subclass of a ModelForm, using the one of the robos85 question :

class MixedForm(ProvinceForm):
    speaker = ...
0
On

If you need to use a query for your choices then you'll need to overwrite the __init__ method of your form.

Your first guess would probably be to save it as a variable before your list of fields but you shouldn't do that since you want your queries to be updated every time the form is accessed. You see, once you run the server the choices are generated and won't change until your next server restart. This means your query will be executed only once and forever hold your peace.

# Don't do this
class MyForm(forms.Form):
    # Making the query
    MYQUERY = User.objects.values_list('id', 'last_name')
    myfield = forms.ChoiceField(choices=(*MYQUERY,))

    class Meta:
        fields = ('myfield',)

The solution here is to make use of the __init__ method which is called on every form load. This way the result of your query will always be updated.

# Do this instead
class MyForm(forms.Form):
    class Meta:
        fields = ('myfield',)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # Make the query here
        MYQUERY = User.objects.values_list('id', 'last_name')
        self.fields['myfield'] = forms.ChoiceField(choices=(*MYQUERY,))

Querying your database can be heavy if you have a lot of users so in the future I suggest some caching might be useful.