2
我是django的新手,我試圖驗證表單數據,並且如果發生任何錯誤,將數據傳輸到模板頁面以舊值顯示錶格。如果可能的話,我想在字典中的每個數據顯示模板中的每個字段的django表單錯誤以及模板中的每個正確數據
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>