Django, show ValidationError in template

manosim

I create a registation app, where users can register providing a username, email and a password. What I did is make sure that the email field is unique(as you can see in the code below). But I can't figure out how I can show the error in case the a user enters an email address that is already in use.

View

from django.shortcuts import render
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.core.context_processors import csrf

from forms import RegistrationForm

# Create your views here.
def register_user(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('../../membership/register_success')
        else:
            return HttpResponseRedirect('../../membership/register_failed')

    args = {}
    args.update(csrf(request))

    args['form'] = RegistrationForm()

    return render(request,'registration/registration_form.html', args)

def register_success(request):
    return render_to_response('registration/registration_success.html')

def register_failed(request):
    return render_to_response('registration/registration_failed.html')

Form

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from django.utils.translation import ugettext_lazy as _

    # forms.py
    class RegistrationForm(UserCreationForm):
        email = forms.EmailField(required=True)

        class Meta:
            model = User
            fields = ('username', 'email', 'password1', 'password2')

        def clean_email(self):
            email = self.cleaned_data.get('email')
            username = self.cleaned_data.get('username')

            if email and User.objects.filter(email=email).exclude(username=username).count():
                raise forms.ValidationError(_("This email address is already in use. Please supply a different email address."))
            return email

        def save(self, commit=True):
            user = super(RegistrationForm, self).save(commit=False)
            user.email = self.cleaned_data['email']
            if commit:
                user.save()
            return user

registration.html

    {% extends "base.html" %}
    {% block title %}Registration{% endblock %}

    {% block content %}

            <h1>Registration</h1>

            {% if form.errors %}
            <h1>ERRORRRRRR same email again???</h1>
            {% endif %}

            {% if registered %}
            <strong>thank you for registering!</strong>
            <a href="../../">Return to the homepage.</a><br />
            {% else %}
            <strong>register here!</strong><br />

            <form method="post" action="/membership/register/">{% csrf_token %}
                {{ form }}
                <input type="submit" name="submit" value="Register" />
            </form>
            {% endif %}

    {% endblock %}
Bibhas Debnath

You're showing the form with {{ form }} on the template. That itself should show all the validation errors by default, but in your case, you're redirecting to some other page if the form is invalid. So you can never show the errors unless you pass the errors with the GET parameters. You could change your view to this to get the errors on the signup page itself -

def register_user(request):
    args = {}
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('../../membership/register_success')
    else:
        form = RegistrationForm()
    args['form'] = form

    return render(request,'registration/registration_form.html', args)

How this works is, if the request method is POST, the form gets initiated with the POST data, then it's validated with the is_valid() call, so the form object now has the validation error messages if it's invalid. If it's valid, it's saved and redirected. If not valid, it comes to the args['form'] = form part where the form object with the error messages is set to the context and then passed to render.

If the request method is not POST, then a form object with no data is instantiated and passed to render().

Now your template should show all the error messages just below each field if there is any error.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

How to show the show ValidationError in template

From Dev

django doesn't show ValidationError

From Dev

Show the dictionary key in django template

From Dev

How to show an ImageField in Django template

From Dev

Django - ValidationError does not display

From Dev

ValidationError with Datatime field in Django

From Dev

ValidationError in FormView Django

From Dev

django template show only distinct value

From Dev

How to show objects count in Django template

From Dev

Show initial value for FileField in django-template

From Dev

django: template show timezone also for the datetime

From Dev

Django Template - show many-to-many relationship

From Dev

Show ASCII characters in django template (python 2)

From Dev

How to show all user list on template in django

From Dev

Show initial value for FileField in django-template

From Dev

Django template doesn't show model items

From Dev

Test django forms raised ValidationError

From Dev

Django Admin ValidationError on save with inlines

From Dev

Django template truncate list to show first n elements

From Java

How to show the total count of online friends in the template (django)?

From Dev

Django template tag to show null date as "still open"

From Dev

Django CMS – Show different content for users and guests in same template

From Dev

Django allauth - using custom form Validation errors do not show on the template

From Dev

Django-cms show_breadcrumb template tag

From Dev

Django CMS – Show different content for users and guests in same template

From Dev

JSONField Django template doesn't show me what I went

From Dev

django ImageField link doesn't show in html template

From Dev

validating email in registration is not raising validationError in Django?

From Dev

Django DateTimeField ValidationError: value has an invalid format

Related Related

  1. 1

    How to show the show ValidationError in template

  2. 2

    django doesn't show ValidationError

  3. 3

    Show the dictionary key in django template

  4. 4

    How to show an ImageField in Django template

  5. 5

    Django - ValidationError does not display

  6. 6

    ValidationError with Datatime field in Django

  7. 7

    ValidationError in FormView Django

  8. 8

    django template show only distinct value

  9. 9

    How to show objects count in Django template

  10. 10

    Show initial value for FileField in django-template

  11. 11

    django: template show timezone also for the datetime

  12. 12

    Django Template - show many-to-many relationship

  13. 13

    Show ASCII characters in django template (python 2)

  14. 14

    How to show all user list on template in django

  15. 15

    Show initial value for FileField in django-template

  16. 16

    Django template doesn't show model items

  17. 17

    Test django forms raised ValidationError

  18. 18

    Django Admin ValidationError on save with inlines

  19. 19

    Django template truncate list to show first n elements

  20. 20

    How to show the total count of online friends in the template (django)?

  21. 21

    Django template tag to show null date as "still open"

  22. 22

    Django CMS – Show different content for users and guests in same template

  23. 23

    Django allauth - using custom form Validation errors do not show on the template

  24. 24

    Django-cms show_breadcrumb template tag

  25. 25

    Django CMS – Show different content for users and guests in same template

  26. 26

    JSONField Django template doesn't show me what I went

  27. 27

    django ImageField link doesn't show in html template

  28. 28

    validating email in registration is not raising validationError in Django?

  29. 29

    Django DateTimeField ValidationError: value has an invalid format

HotTag

Archive