[Answer]-Reference objects using foreign keys in Django forms

1👍

You need to override the field query set in form initialization:

class SketchForm(forms.ModelForm):
    wish = forms.ModelChoiceField(queryset= Sketch.objects.all(), initial=0)
    image_temp = forms.CharField(help_text='Imagine this is an upload button for image, write anything')

    def __init__(self, *args, **kwargs):
        wish_qs = kwargs.pop('wish_qs')
        super(SketchForm, self).__init__(*args, **kwargs)
        self.fields['wish'].queryset = wish_qs

    class Meta:
        model = Sketch
        fields = ('wish', 'image_temp')

And in your view, you need to pass a queryset filtered based on current logged in user:

sketch_form = SketchForm(request.POST, wish_qs=Wish.objects.filter(wisher=request.user))

and:

sketch_form = SketchForm(wish_qs=Wish.objects.filter(wisher=request.user))

Leave a comment