The Django model model removes the “required” attribute based on a different field selection

I have a ModelForm with multiple fields. Some fields are required, some are not. I also have a “Selection” field with different options, and I want some fields to be “necessary” or not based on this choice of choice.

I tried the clean () method of the form

def clean(self): cleaned_data = self.cleaned_data some_field = cleaned_data.get("some_field") if some_field == 'some_value': self.fields['other_field'].required = False return cleaned_data 

but it does not work

+7
source share
3 answers

See Django's documentation on Cleaning and checking fields that depend on each other . Standard practice would be as follows:

 def clean(self): cleaned_data = self.cleaned_data some_field = cleaned_data.get("some_field") if some_field == 'some_value': # 'other_field' is conditionally required. if not cleaned_data['other_field']: raise forms.ValidationError("'Other_field' is required.") return cleaned_data 
+10
source

If you like to print an error message for the required field in the usual way, you can do this:

 def clean(self): cleaned_data = super(PasswordChangeForm, self).clean() token = cleaned_data.get('token') old_password = cleaned_data.get('old_password') if not token and not old_password: self._errors['old_password'] = self.error_class([self.fields['old_password'].error_messages['required']]) 
+2
source

You have the right idea, but the problem is that separate field checks were already done before the form was clean. You have a couple of options. You can make the field unnecessary and process the logic when necessary in your form.clean . Or you can leave the field as necessary and remove validation errors that it can raise in its purest form.

 def clean(self): cleaned_data = self.cleaned_data some_field = cleaned_data.get("some_field") if some_field == 'some_value': if 'other_field' in self.errors: del self.errors['other_field'] cleaned_data['other_field'] = None return cleaned_data 

This has some problems in that it removes all errors, not just missing / necessary errors. There is also a problem with cleaned_data . Now you have a required field that is not in cleaned_data, so I added it as None . The rest of your application will need to handle this case. It may seem odd to have a required field that doesn't matter.

+1
source

All Articles