Home > database >  Validation error message isn't showing in django
Validation error message isn't showing in django

Time:08-30

The validation error Password not matched isn't showing if I separately access the fields like {{form.psrd}} (password field) and {{form.rpsrd}} (Re-Type password field). But error message shows if I use {{form.as_p}}.

This is my forms.py:

from django import forms


class formdata(forms.Form):
    name = forms.CharField(
        max_length=20, widget=forms.TextInput(attrs={'class': 'input'}))
    email = forms.EmailField(widget=forms.TextInput(attrs={'class': 'input'}))
    psrd = forms.CharField(min_length=8, widget=forms.PasswordInput(
        attrs={'class': 'input'}), label='Password')
    rpsrd = forms.CharField(min_length=8, widget=forms.PasswordInput(attrs={'class': 'input'}),
                            label='Re-Type Password')

    def clean(self):
        cleaned_data = super().clean()

        p = self.cleaned_data['psrd']
        rp = self.cleaned_data['rpsrd']

        if p != rp:
            raise forms.ValidationError('Password not matched')

Body of regi.html :

<body>
    <form method="post">{% csrf_token %}
        <label>
            <p >ENTER YOUR NAME</p>
            {{form.name}}
            <div >
                <div ></div>
            </div>
        </label>

        <label>
            <p >ENTER YOUR EMAIL</p>
            {{form.email}}
            <div >
                <div ></div>
            </div>
        </label>

        <label>
            <p >ENTER YOUR PASSWORD</p>
            {{form.psrd}}
            <div >
                <div ></div>
            </div>
        </label>

        <label>
            <p >RE-ENTER YOUR PASSWORD</p>
            {{form.rpsrd}}
            <div >
                <div ></div>
            </div>
        </label>

        <button type="submit">submit</button>
    </form>
</body>

CodePudding user response:

As Django Docs explains on rendering form manually, you need to add two more tags:

{{ form.non_field_errors }} For errors not coming from explicit fields

and {{ form.field.errors }} for field errors. So in your template:

 <label>
            <p >RE-ENTER YOUR PASSWORD</p>
            {{ form.rpsrd }}
            {% if form.rpsrd.errors %}
                <div >{{ form.rpsrd.errors }}</div>
            {% endif %}
            <div >
                <div ></div>
            </div>
        </label>
  • Related