Django登陆验证

# 导入django form模块
#bookmarks/forms.py
from django import forms

class RegistrationForm(forms.Form):
username=forms.CharField(lable=u'用户名',max_length=30)
email=forms.EmailField(u'邮箱')
password1=forms.CharField(
lable=u'密码',
widget=forms.PasswordInput()
)

password2=forms.CharField(
lable=u'确认密码',
widget=forms.PasswordInput()
)

# form bookmarks.forms import *
# form=RegistrationForm()
# print form.as_table()
# print form['username']

#检查两次密码一致性
defclean_password2(self):
if 'password1' in self.clean_data:
password1=self.cleaned_data['password1']
password2=self.cleaned_data['password2']
if password1==password2:
return password2
raise forms.ValidationError('两次密码不一样')

import re
from django.contrib.auth.models import User

defclean_username(self):
username=self.cleaned_data['username']
# ^w+$  //匹配由数字、26个英文字母或者下划线组成的字符串
if not re.search(r'^w+$',username):
raise forms.ValidationError('请输入合法的用户名')
try:
User.objects.get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError('用户名被占用')

# bookmarks/view.py

from bookmarks.forms import *
def register_page(request):
ifrequest.method=='POST':
form=RegistrationForm(request.POST)
if form.is_valid():
username=User.objects.creat_user(
username=form.cleaned_date['username']
password=form.cleaned_date['password1']
email=form.cleaned_date['email']
)
return HttpResponseRedirect('/')
else:
form=RegistrationForm()
variables=RequestContext(request,{
form:form
})
return render_to_response('registration/register.html',
variables
)

# templates/registration/register.html

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


{{form.as_p}}


{% endblock %}

# urls.py

(r'^register/$',register_page),

转载于:https://www.cnblogs.com/lushijie/archive/2013/05/24/3311214.html

你可能感兴趣的:(Django登陆验证)