vZ10
vZ10

Reputation: 2686

Restrict one field of form depending on value of another field

I have three models like that:

class SchoolClass(models.Model):
     school = models.ForeignKey(School)
     class_name = models.CharField(max_length=5)

class School(models.Model):
     name = models.CharField(max_length=100)
     address = models.TextField(blank=True)

class Student(models.Model):
    school = models.OneToOneField(School, null=True)
    class_id = models.ForeignKey(SchoolClass)
    user = models.OneToOneField(User, on_delete=models.CASCADE)

I create Django Form for the Student, is there any way to setup Form to show only classes which are in school I've chosen?

Upvotes: 0

Views: 567

Answers (1)

Mac Chaffee
Mac Chaffee

Reputation: 110

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)

Upvotes: 1

Related Questions