条件满足时排除django表单字段

时间:2015-08-20 21:45:38

标签: python django django-forms

我正在尝试在满足某些条件时从django表单中排除表单字段。即使我提供有效条件,表单也会在不排除字段的情况下呈现。

这就是我在做的事情:

#views.py
def create_exam(request):
    cc = is_cc(request.user)
    form = ExamCreateForm(cc)
    return render(request, 'exam/exam_create.html', {'form': form})

#forms.py
class ExamCreateForm(forms.ModelForm):

    def __init__(self, cc, *args, **kwargs):
        if cc:
            self.Meta.exclude.append('section')
        super(ExamCreateForm, self).__init__(*args, **kwargs)

    class Meta(object):
        model = Exam
        exclude = []

即使ccTrue,表单仍会呈现section字段。

我在哪里弄错了?

1 个答案:

答案 0 :(得分:3)

class ExamCreateForm(forms.ModelForm):
    class Meta:
        model = Exam
        fields = '__all__'

    def __init__(self, cc, *args, **kwargs):
        super(ExamCreateForm, self).__init__(*args, **kwargs)
        if cc:
            del self.fields['section']