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.
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' }),
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With