简体   繁体   中英

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
    )

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM