[Python] Change Django required form field to False

Discussão em 'Python' iniciado por Stack, Fevereiro 6, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to change the required of a form field to 'False' depending on the input of another field.

    form:

    class MyNewForm(forms.Form):

    def __init__(self, *args, **kwargs):
    self.users = kwargs.pop('users', None)
    super(MyNewForm, self).__init__(*args, **kwargs)


    self.fields['name'] = forms.CharField(
    max_length=60,
    required=True,
    label="Name *:",
    widget=forms.TextInput(
    attrs={'class' : 'form-control', 'placeholder': 'Name'})
    )

    def clean_this_other_field(self):

    # change required field
    name = self.fields['name']
    print name.required
    name.required=False
    print name.required


    results of print:

    True

    False

    So the field required is changing to 'False' but when the form page reloads it reverts back to 'True'

    Any suggestions?


    EDIT - Problem solved
    ​

    For anyone landing on this with a similar issue:

    def clean_remove(self):
    cleaned_data = super(MyNewForm, self).clean()
    remove = cleaned_data.get('remove', None)
    if remove:
    self.fields['name'].required=False


    Remove is the first field in the form so adding this clean on the remove field resolves the issue.

    Continue reading...

Compartilhe esta Página