[Answered ]-How can I filter objects when building a form from a model in Django?


You can pass in the request as an argument to the TriggerForm and then use that to filter the Schedule…

class TriggerForm(ModelForm):
    class Meta:
        model = Trigger

    def __init__(self, request=None, *args, **kwargs):
        super(TriggerForm, self).__init__(*args, **kwargs)

        self.fields['schedule'] = forms.ModelChoiceField(queryset=Schedule.objects.filter([your filter here based on the logged in user]))


from my_app.forms import TriggerForm

def my_view(request):
    form = TriggerForm(request, request.POST or None)
    # and so on

Hope that helps you out.

Leave a comment