forms表單
#_*_coding:utf-8_*_ from django import forms class regis(forms.Form): username = forms.CharField(label=u'用戶名',min_length=4,max_length=20,error_messages={'required':u'用戶名不能為空哦','min_length':u'用戶名長度不能小於4位哦','max_length':u'用戶名長度不能大於20位哦'}) password = forms.CharField(label=u'密碼',min_length=6,max_length=256,widget=forms.PasswordInput,error_messages={'required':u'密碼不能為空哦','min_length':u'密碼長度不能小於6位哦'}) cpassword = forms.CharField(label=u'確認密碼',min_length=6, max_length=256, widget=forms.PasswordInput(attrs={'class':'form-control','placeholder':u'與上面密碼保持一致'}),error_messages={'required': u'密碼不能為空哦', 'min_length': u'密碼長度不能小於6位哦'})
models模型
#coding=utf-8 from django.db import models class Userinfo(models.Model): username = models.CharField(unique=True,max_length=20) password = models.CharField(max_length=256) def __unicode__(self): return self.username
views視圖
#conding=utf-8 from django.shortcuts import render,redirect from django.http import HttpResponse,Http404 from forms import * from models import Userinfo from hashlib import sha1 def register(request): if request.method == 'POST': form = regis(request.POST) if form.is_valid(): user = form.cleaned_data['username'] pwd = form.cleaned_data['password'] cpwd = form.cleaned_data['cpassword'] # encryption sh1 = sha1() sh1.update(pwd.encode('utf-8')) pwdd = sh1.hexdigest() if pwd != cpwd: return redirect('/') Userinfo.objects.get_or_create(username=user,password=pwdd) msg='user register success!' return render(request,'info.html',{'msg':msg}) else: error_msg = form.errors return render(request, 'register.html', {'form': form, 'errors': error_msg}) else: form = regis() return render(request, 'register.html', {'form': form})
注意視圖的次序:這里的邏輯很重要
if request.method == 'POST': form = regis(request.POST) if form.is_valid():
使用表單進行數據提交時,不需要指定form的action,自動提交到展示頁面的視圖,切記注意
先判斷是提交信息還是普通訪問
如果不是提交信息,那么就打開注冊頁面同時攜帶表單對象,如果是post提交,就獲取forms表單regis提交上來的信息
再判斷表單內容是否符合格式要求,如果符合再判斷兩次輸入的密碼是否相等,如果相等則進行數據插入的操作,並且返回info.html頁面告知用戶注冊成功
如果表單內容不符合格式要求,則將forms表單中的非空,長度限制等信息返回到注冊頁面
注冊頁面register.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Login</title> <style type="text/css"> .ff{ margin-top:300px; margin-left:500px; } #log{ background-color:#ccc; margin:0px auto; } </style> </head> <body> <div id="log"> <form method="post" class="ff"> {% csrf_token %} <table> <tr><td>{{form.username.label_tag}}</td><td>{{form.username}}</td></tr> <tr style="color:red"><td>{{errors.username}}</td></tr> <tr><td>{{form.password.label_tag}}</td><td>{{form.password}}</td></tr> <tr style="color:red"><td>{{errors.password}}</td></tr> <tr><td>{{form.cpassword.label_tag}}</td><td>{{form.cpassword}}</td></tr> <tr style="color:red"><td>{{errors.cpassword}}</td></tr> <tr><td><input type="reset" value="重置"></td><td style="text-align:right"><input type="submit" value="提交"></td></tr> </table> </form> </div> </body> </html>