1👍
✅
The problem is because you’re not filtering the model fields by your user in the ExpenseForm
(like you are doing in the ExpenseListView.get_queryset
).
To do it, you will need to change a bit your logic. you can try something like this:
# forms.py
class ExpenseForm(forms.ModelForm):
def __init__(self, user, *args, **kwargs):
super().__init__(*args, **kwargs)
# limit the category field queryset
self.fields['category'] = forms.ModelChoiceField(
queryset=user.category.all())
)
class Meta:
model = Expense
fields = ('name', 'amount', 'category')
# views.py
class ExpenseCreateView(CreateView):
...
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
# inject the user in the form instantiation
kwargs['user'] = self.request.user
return kwargs
👤JoVi
Source:stackexchange.com