Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Django required form field to False

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.

like image 427
drew Avatar asked Jan 04 '23 12:01

drew


1 Answers

Can you give more of your code when this problem appers?

If u use ModelForm you can do something like:

class YourForm(forms.ModelForm):    
    def __init__(self, *args, **kwargs):
        super(YourForm, self).__init__(*args, **kwargs)
        self.fields['name'].required = True

    class Meta:
        model = YouModel
        fields = (...)

Django Model Forms - Setting a required field

U can add required using widget too:

email = forms.EmailField(
    max_length=100,
    required=True,
    widget=forms.TextInput(attrs={ 'required': 'true' }),
)
like image 52
Thaian Avatar answered Jan 06 '23 01:01

Thaian