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

后端 未结 3 1140
被撕碎了的回忆
被撕碎了的回忆 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: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)
    

提交回复
热议问题