[Fixed]-Restrict one field of form depending on value of another field

1👍

I think what you want to do is override the __init__ method of your form so that you can use a query to filter out classes you don’t need. This query needs to know who the currently active student is, so you’ll have to pass the student in as a keyword argument.

Something like this:

class NameOfForm(forms.Form)):
    def __init__(self, *args, **kwargs):
        current_student = kwargs.pop('student', None)
        super(NameOfForm, self).__init__(*args, **kwargs)
        classes_in_school = SchoolClass.objects.filter(school=current_student.school)
        self.fields['name_of_field'] = ModelChoiceField(queryset = classes_in_school, 
                                                        required = True,
                                                        label = "Choose a class")

And then in your view, when you create the form, remember to pass in the current student as an extra argument. Something like this:

form = NameOfForm(request.POST or None, student=request.student)

Leave a comment