Display django form error for each field in template and each correct data in template -
i new django , trying validate form data , if error occurs transfer data template page old values display in form. if possible want error message each data in dictionary
views.py
from django.shortcuts import render .forms import regform # create 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 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 not valid" print form['mail'].errors return render(request, 'register.html') forms.py 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>
from views.py
, pass form object template
... return render(request, 'register.html', { 'form': form }) ...
now, in template, can use object form
rendering purposes. example, first name
field doing:
... <label>first name:</label><br> <input type="text" name="firstname"><br> ...
you should instead:
... <label for="{{ form.firstname.id_for_label }}">first name:</label> {{ form.firstname }} {{ form.firstname.errors }} ...
{{ form.firstname }}
renders html input tag, while {{ form.firstname.errors }}
renders errors field.
finally, use template tag {{ form.non_field_errors }}
(usually @ end or @ top of form) render other errors.
the documentation clear on topic. have @ rendering-fields-manually further information.
Comments
Post a Comment