[Answered ]-Django Formset will not filter by user objects

2👍

It looks like your blogpost field is a ForeignKey. By default this is represented by django.forms.ModelChoiceField. This inherits from ChoiceField whose choices are a model QuerySet. See the reference for ModelChoiceField.

So you want to provide a custom QuerySet to the field’s queryset attribute. This depends a little on how your form is built. I find it easiest to do in the constructor but using the formset factory makes this a little tricky. You might try this after you construct the formset:

formset = imageformset()
for form in formset.forms:
    form.fields['blogpost'].queryset = Blogpost.objects.filter(user=user)

I think you’ll also need to do that before you call formset.is_valid() in the request.method == ‘POST’ branch of the code.

Leave a comment