1.创建Python Django 工程
工程目录结果如图
2.创建form.py 实现表单视图
from django import forms
from django.forms.widgets import Widget
class LoginForm(forms.Form):
us = forms.CharField(label=u'用户名',max_length=100, widget=forms.TextInput(
attrs={'class':'form-control','placeholder':u'用户名','request':'','autofocus':''}),)
pwd = forms.CharField(label=u'密码',widget=forms.PasswordInput(
attrs={'class':'form-control', 'placeholder':u'密码','request':''}))
3.完成视图函数 views.py中
def usLogin(request):
context={}
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():#验证输入是否合法
us = form.cleaned_data['us']#获取输入框中的值
pwd = form.cleaned_data['pwd']
if r.exists('us:%s:id' %us):#判断是否存在key值
uid = r.get('us:%s:id' %us)#获取user id值
if r.exists('user:%s' %uid):
us_, pwd_ = r.hmget('user:%s' %uid, 'username', 'pwd')
if us == us_ and pwd == pwd_:
r.hset('user:%s' %uid, 'last_login_date', datetime.now())
#重定向
return HttpResponseRedirect('/success')
context['msg']=u'用户名或密码错误'
context['form']=form
#第一次访问页面时,调用LoginForm对象显示页面
form = LoginForm()
context['form'] = form
#context_instance=RequestContext(request) 对页面中csrf_token的作用
return render_to_response('index.html', context, context_instance=RequestContext(request))
def home(request):
"""
" 登录成功后跳转的页面
"""
return render(request, 'login.html')
index.html页面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
{% if msg %}
<p>{{ msg }}</p>
{% endif %}
<form action="" method="post">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<input type="submit" value="Submit">
</form>
</body>
</html>
login.html页面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>hello world</h2>
</body>
</html>
urls配置:
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^login/$', views.usLogin),
url(r'^success/$', views.home),
]
Redis 实现User表:
一般一张User表包含以下字段: id,username,pwd,sex,is_active,is_admin,avatar,login_count,last_login_date 等.这里选择Redis实现并用Django完成登陆注册功能.
对于user表Redis Key的设计,我们有两种方案:
(1).user:1:username
的形式
(2).user:1 username value
hash类型的设计
这里选择hash类型在命令行下设置如下:
127.0.0.1:6379> hmset user:1 username BeginMan pwd root sex 1 is_active 1 is_admin 1
OK
127.0.0.1:6379> hgetall user:1
1) "username"
2) "BeginMan"
3)"pwd"
4)"root"
5) "sex"
6) "1"
7) "is_active"
8) "1"
9) "is_admin"
10) "1"
定义一个表用来记录用户名对应的ID
127.0.0.1:6379> set "us:BeginMan:id" 1
OK