2👍
✅
One way to enforce choices on ForeignKey
fields on database level is to use limit_choices_to
argument.
You cannot do this to restrict category
because queryset depends on request.
But you can access request object in ModelForm. So you’ll have to override __init__
of ModelForm to define custom queryset for category
.
class PostForm(forms.ModelForm):
class Meta:
model = Post
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
super(PostForm, self).__init__(*args, **kwargs)
self.fields['category'].queryset = Category.objects.filter(author=user)
Source:stackexchange.com