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

后端 未结 3 1134
被撕碎了的回忆
被撕碎了的回忆 2020-12-09 03:59

I am trying to use the ModelForm to add my data. It is working well, except that the ForeignKey dropdown list is showing all values and I only want it to display the values

相关标签:
3条回答
  • 2020-12-09 04:15

    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 讨论(0)
  • 2020-12-09 04:37

    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)
    
    0 讨论(0)
  • 2020-12-09 04:37

    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")
    
    0 讨论(0)
提交回复
热议问题