[Fixed]-Changing Django form property 'required' by bool in template

1👍

You probably don’t want to change base_fields – that updates the fields of the StudentDetailForm class, not just the particular form instance

Depending on the rest of your view, setting form.fields['first_name'].required should work.

However, it’s normally better to set self.fields['first_name'].required inside the form’s __init__ method. I’m not sure how you would do this because you seem to have multiple forms and many field names, so here’s a simpler example.

class MyForm(forms.Form):
    first_name = forms.CharField()

    def __init__(self, *args, **kwargs):
        first_name_required = kwargs.pop('first_name_required')
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['first_name'].required = first_name_required

You would then initialise your form like:

form = MyForm(data=request.POST, first_name_required=True)

Leave a comment