Percy3872
Percy3872

Reputation: 17

How to filter values in a drop down list django

I am populating my drop down box with values from my model, I have five values in my model, I only want to show three of these values in this particular instance how would I achieve this.

forms.py

class namesForm(forms.Form):
    names = forms.ModelChoiceField(
        queryset=Names.objects.order_by('name').exclude(name='Josh','Tom'),
        label = "Name:",
        widget = Select(attrs={'class': 'span6 small-margin-top small-margin-bottom'}),
        empty_label = "Select a Name",
        required=True
    )

Upvotes: 0

Views: 965

Answers (1)

Brian H.
Brian H.

Reputation: 844

Based on your forms.py code, i assume this is what you want:

class namesForm(forms.Form):
    names = forms.ModelChoiceField(
        queryset=Names.objects.exclude(name__in=['Josh','Tom']).order_by('name'),
        label = "Name:",
        widget = Select(attrs={'class': 'span6 small-margin-top small-margin-bottom'}),
        empty_label = "Select a Name",
        required=True
    )

Line I changed:

queryset=Names.objects.exclude(name__in=['Josh','Tom']).order_by('name'),

Documentation on using __in:
https://docs.djangoproject.com/en/1.10/ref/models/querysets/#in

Upvotes: 1

Related Questions