djangodjango-formsdjango-templates

Display django form error for each field in template and each correct data in template


I am new to django and i am trying to validate form data and if any error occurs transfer that data to the template page with the old values to display in the form. If possible i want the error message for each data in dictionary

views.py

from django.shortcuts import render

from .forms import RegForm

# Create your views here.
def login(request):

    return render(request, 'login.html')

def registration(request):
    if request.method == 'POST':
        form = RegForm(request.POST)

        if form.is_valid():
            print "Form is valid"
            print form.cleaned_data

            user_data = {
                'firstname':form.cleaned_data['firstname'],
                'lastname':form.cleaned_data['secondname'],
                'username': form.cleaned_data['username'],
                'mail':form.cleaned_data['mail'],
                'password': form.cleaned_data['password']}
            print user_data
        else:
            print "Form is not valid"
            print form['mail'].errors
    return render(request, 'register.html')
   forms.py



    from django import forms

    class RegForm(forms.Form):

        firstname = forms.CharField(max_length=100)
        secondname = forms.CharField(max_length=100)
        username = forms.CharField(max_length=100, min_length=8)
        mail = forms.EmailField()
        password = forms.CharField(widget = forms.PasswordInput(), min_length=8, max_length=100)

register.html

     <!DOCTYPE html>
    <html>
        <head>
            <title>registration</title>
            <style type="text/css">
                header{
                    width: 100%;
                    display: block;
                }
                section{
                    width: 180px;
                    margin: auto;
                    display: block;
                }
                nav{
                    width: 180px;
                    float: right;
                    display: block;
                }

            </style>
    </head>
    <body>
        <header>
            <nav>
                <a href="{% url 'registration' %}">Registration</a>
                <a href="{% url 'login' %}">Login</a>
            </nav>
        </header>
        <section>
        <h1 align="center">Register:</h1>
            <form method = "post" action = "{% url 'registration' %}">
                {% csrf_token %}
                <label>First Name:</label><br>
                <input type="text" name="firstname"><br>
                <label>Second Name:</label><br>
                <input type="text" name="secondname"><br>
                <label>Mail Id:</label><br>
                <input type="text" name="mail"><br>
                <label>User Name:</label><br>
                <input type="text" name="username" value=""><br>
                <label>Password:</label><br>
                <input type="password" name="password"><br><br>
                <input type="submit" name="submit" value="submit">
            </form>
        </section>

    </body>
</html>

Solution

  • From your views.py, pass the form object to the template

     ...
    return render(request, 'register.html', { 'form': form })
     ...
    

    Now, in the template, you can use the object form for rendering purposes. For example, for your First Name field you were doing:

     ...
     <label>First Name:</label><br>
     <input type="text" name="firstname"><br>
     ...
    

    You should do this instead:

     ...
     <label for="{{ form.firstname.id_for_label }}">First Name:</label>
       {{ form.firstname }}
       {{ form.firstname.errors }}
     ...
    

    {{ form.firstname }} renders you html input tag, while {{ form.firstname.errors }} renders errors for this field.

    Finally, you could also use the template tag {{ form.non_field_errors }} (usually at the end or at the top of the form) to render other errors.

    The documentation is very clear on this topic. Have a look at rendering-fields-manually for further information.