RaoufM
RaoufM

Reputation: 555

Can't use validation error for a form in django

I have a birthday field in a model and when i try to validate the form i want it so that the age should be 13+ to validate the form . I have set up something like this

.forms.py

class RegistrationForm(UserCreationForm):
    email = forms.EmailField(max_length=60, help_text='Add a valid email')
    today = date.today()

    class Meta:
        model = Account
        fields = ('email','username', 'password1', 'password2',
            'first_name','last_name','addresse','birthday','city','profil_pic')
        def clean_birth(self):
            birthday = self.cleaned_data['birthday']
            if int((today-birthday).days / 365.25) < 18:
                raise forms.ValidationError("Users must be 18+ to join the website")`

template

<form method="post">
    {% csrf_token %}
    {{registration_form.as_p}}
    {% if registration_form.errors %}
        {% for field in registration_form %}
            {% for error in field.errors %}
                <div class="alert alert-danger">
                    <strong>{{ error|escape }}</strong>
                </div>
            {% endfor %}
        {% endfor %}
        {% for error in registration_form.non_field_errors %}
            <div class="alert alert-danger">
                <strong>{{ error|escape }}</strong>
            </div>
        {% endfor %}
      {% endif %}
        <button type="submit">zef</button>
    </form>

But this only show the main errors of django like wrong email and passwords not matching

Upvotes: 0

Views: 72

Answers (1)

weAreStarsDust
weAreStarsDust

Reputation: 2752

As Docs says

The clean_<fieldname>() method is called on a form subclass – where is replaced with the name of the form field attribute.

rename method from def clean_birth(self) to def clean_birthday(self)

And change indent to left for clean_birthday() method. Now it's method of class Meta, but it should be method of class RegistrationForm

class RegistrationForm(UserCreationForm):
    email = forms.EmailField(max_length=60, help_text='Add a valid email')
    today = date.today()

    class Meta:
        model = Account
        fields = ('email','username', 'password1', 'password2',
            'first_name','last_name','addresse','birthday','city','profil_pic')
    def clean_birthday(self):
        birthday = self.cleaned_data['birthday']
        if int((today-birthday).days / 365.25) < 18:
            raise forms.ValidationError("Users must be 18+ to join the website")`

Upvotes: 1

Related Questions