v1k45
v1k45

Reputation: 8250

Excluding django form fields when condition met

I am trying to exclude a form field from django forms when some conditions are met. Even when i supply valid conditions, the form renders without excluding the field.

here is what i am doing:

#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 = []

Even when the cc is True the form still renders the section field.

Where am i making mistake?

Upvotes: 0

Views: 1086

Answers (1)

Ajay Gupta
Ajay Gupta

Reputation: 1285

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']

Upvotes: 3

Related Questions