简体   繁体   中英

how to ensure that only my custom clean_field is called when a form is submitted?

I have a django form like this :

class PatientForm(forms.Form):
    patient_id = forms.IntegerField()
    patient_national_code = forms.CharField()

and I have a custom clean_ method for this form:

def clean_patient_national_code(self):
    patient_national_code = self.cleaned_data['patient_national_code']
    if not patient_national_code:
        raise forms.ValidationError("My Error!")
    return patient_national_code

but when I try to submit a form that its national_code field is empty(and should return "MY Error!"), it returns "This field is required." error. I think that it is the error that django's default validator returns, what should I do to get "My Error!" instead of django's default error?

Add required=False in the field definition, in that case django will not perform the check and will call your clean method.

However, note than when this field is not in the form data, accessing it as self.cleaned_data['patient_national_code'] may result in KeyError .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM