[Django]-How do I filter values in a Django form using ModelForm?

34👍

You can customize your form in init

class ExcludedDateForm(ModelForm):
    class Meta:
        model = models.ExcludedDate
        exclude = ('user', 'recurring',)
    def __init__(self, user=None, **kwargs):
        super(ExcludedDateForm, self).__init__(**kwargs)
        if user:
            self.fields['category'].queryset = models.Category.objects.filter(user=user)

And in views, when constructing your form, besides the standard form params, you’ll specify also the current user:

form = ExcludedDateForm(user=request.user)

1👍

Here example:

models.py

class someData(models.Model):
    name = models.CharField(max_length=100,verbose_name="some value")

class testKey(models.Model):
    name = models.CharField(max_length=100,verbose_name="some value")
    tst = models.ForeignKey(someData)

class testForm(forms.ModelForm):
    class Meta:
        model = testKey

views.py

...
....
....
    mform = testForm()
    mform.fields["tst"] = models.forms.ModelMultipleChoiceField(queryset=someData.objects.filter(name__icontains="1"))
...
...

Or u can try something like this:

class testForm(forms.ModelForm):
    class Meta:
        model = testKey

def __init__(self,*args,**kwargs):
    super (testForm,self ).__init__(*args,**kwargs)
    self.fields['tst'].queryset = someData.objects.filter(name__icontains="1")
👤Saff

1👍

I know this is old; but its one of the first Google search results so I thought I would add how I found to do it.

class CustomModelFilter(forms.ModelChoiceField):
    def label_from_instance(self, obj):
        return "%s %s" % (obj.column1, obj.column2)

class CustomForm(ModelForm):
    model_to_filter = CustomModelFilter(queryset=CustomModel.objects.filter(active=1))

    class Meta:
        model = CustomModel
        fields = ['model_to_filter', 'field1', 'field2']

Where ‘model_to_filter’ is a ForiegnKey of the “CustomModel” model

Why I like this method:
in the “CustomModelFilter” you can also change the default way that the Model object is displayed in the ChoiceField that is created, as I’ve done above.

0👍

is the best answer:
BookDemoForm.base_fields[‘location’] = forms.ModelChoiceField(widget=forms.Select(attrs={‘class’: ‘form-control select2’}),queryset=Location.objects.filter(location_for__fuel=True))

Leave a comment