根据另一个字段的值限制一个表单字段

时间:2016-06-01 11:20:33

标签: django django-models django-forms

我有三个这样的模型:

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)

我为学生创建了Django表单,有没有办法设置表单只显示我在学校选择的课程?

1 个答案:

答案 0 :(得分:1)

我认为您要做的是覆盖表单的__init__方法,以便您可以使用查询来过滤掉您不需要的课程。此查询需要知道当前活跃的学生是谁,因此您必须将学生作为关键字参数传递。

这样的事情:

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")

然后在您看来,当您创建表单时,请记住将当前学生作为额外参数传递。像这样:

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