网站建立的第一步,用户的登录验证和新用户注册。
django自带了用户管理(暂时不用),下面自己写一个认证登录:
先建一个html表单页面:
post请求地址为当前的login页面;
<form id="formid" name="myform" method='post' action='login'>
<table width="100%" border="0">
<tr>
<td width="60" height="40" align="right">用户名td>
<td>
<input type="text" value="" name="username" id="userid" />
td>
tr>
<tr>
<td width="60" height="40" align="right">密 码td>
<td>
<input type="password" value="" name="userpass" id="userpassid" />
td>
tr>
<tr>
<td width="60" height="40" align="right">td>
<td>
<div class="c4">
<input type="submit" value="确 认 登 录" class="btn2" />
div>
td>
tr>
table>
form>
显示login页面,提交post请求:
**RequestContext(request))*用于放置post请求
views.py
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
# Create your views here.
def login(request):
return render_to_response('login.html', context_instance=RequestContext(request))
处理post请求,显示在页面上:
**request.POST[‘inputUserName’]**获取post表单的数据[ ]为控件的name属性;
def submit(request):
if 'username' in request.POST:
username = request.POST['username']
password=request.POST['userpass']
else:
username = "Not inputUserName"
ctx={
'user':username,
'pass':password,
}
return render_to_response('login.html', ctx,)
在login.html
页面中添加{{ user}} {{ pass }}
url(r’^$’, demo_views.login),
url(r’^submit$’,demo_views.submit),
对于出现的问题
CSRF验证失败. 相应中断.
看上面的提示是防止CSRF.也就是安全方面的,防止跨站请求伪造.
可能出现这个问题
百度了一下:
解决步骤:
1〉django工程settings.py
django.middleware.csrf.CsrfViewMiddleware 确认存在
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',#确认存在
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
2〉html中的form添加模板标签{% csrf_token %}
3〉django工程views.py
使用 render_to_response
from django.shortcuts import render_to_response
from django.template import RequestContext
def some_view(request):
# ...
return render_to_response('my_template.html',
my_data_dictionary,
context_instance=RequestContext(request))
有疑问请戳Cross Site Request Forgery protection
P.S如果要屏蔽CSRF
方法1:注释掉django工程settings.py中
#'django.middleware.csrf.CsrfViewMiddleware'
方法2:django工程views.py添加屏蔽装饰器
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def some_view(request):
#...