سؤال

I have scoured related SO posts and Django docs, can't quite get it to work. My form:

from django import forms

class SignUpForm(forms.Form):
    (...)
    email              = forms.EmailField(max_length=50)
    email_conf         = forms.EmailField(max_length=50)

    def clean(self):
        form_data = self.cleaned_data

        if form_data['email'] != form_data['email_conf']:
            self._errors['email_conf'] = 'Emails do not match.'   # attempt A
            self.add_error('email', 'Emails do not match.')       # attempt B
            raise forms.ValidationError('Emails do not match.')   # attempt C
        return form_data

If the emails do NOT match, I'd like for Django to use my message string in the same manner as its other validations -- as a <li> element of <ul class='errorlist'> under the 'email_conf' field.

From the three attempts above, the only one that actually seems to do something is #A, but the message is inserted into the {{ form.email_conf.errors }} template as a plain string (not as a list item).

The other two attempts do not do anything, and in ALL cases if either field is empty, Django now throws KeyError.

Would love to know what's the correct way to achieve the result I'm after. Thanks!

هل كانت مفيدة؟

المحلول

Looks like you should use error_class method of the form, like in example here. Also you should delete 'email_conf' element from cleaned_data dict. It's also very important to make sure all the keys do present in cleaned data (that these keys validated on previous steps of validation).

def clean(self):
    cleaned_data = super(SignUpForm, self).clean()
    email = cleaned_data.get('email')
    email_conf = cleaned_data.get('email_conf')

    if email and email_conf and email != email_conf:
        self._errors['email_conf'] = self.error_class(['Emails do not match.'])
        del self.cleaned_data['email_conf']
    return cleaned_data
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top