Custom form validation

主宰稳场 提交于 2019-11-27 17:10:26

To validate a single field on it's own you can use a clean_FIELDNAME() method in your form, so for email:

def clean_email(self):
    email = self.cleaned_data['email']
    if User.objects.filter(email=email).exists():
        raise ValidationError("Email already exists")
    return email

then for co-dependant fields that rely on each other, you can overwrite the forms clean() method which is run after all the fields (like email above) have been validated individually:

def clean(self):
    form_data = self.cleaned_data
    if form_data['password'] != form_data['password_repeat']:
        self._errors["password"] = ["Password do not match"] # Will raise a error message
        del form_data['password']
    return form_data

I'm not sure where you got clean_message() from, but that looks like it is a validation method made for a message field which doesn't seem to exist in your form.

Have a read through this for more details:

https://docs.djangoproject.com/en/dev/ref/forms/validation/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!