環(huán)境:python3.6 django2.1
今天照著一本書上練習django的session功能時彪置,發(fā)現(xiàn)使用form表單提交時總是403錯誤显熏,我在form表單中也使用了{% csrf_token %}
,其他的感覺也沒錯伦吠,但是折騰了一上午鞍历,我發(fā)現(xiàn)是按照書上的思路導致我形成的思維定式了,根源是出在views.py中榜贴,說起來,知道錯誤后感覺自己好二妹田。唬党。。話不多說鬼佣,直接上代碼了
login.html的代碼
<!-- login.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登陸分享日記</title>
</head>
<body>
<nav>
<div>分享日記</div>
<ul>
<li><a href="/">HOME</a></li>
{% if username %}
<li><a href="/logout">注銷</a></li>
<li><a href="/post">寫日記</a></li>
<li><a href="/admin">后臺管理</a></li>
{% else %}
<li><a href="/login">登陸</a></li>
<li><a href="/contact">聯(lián)絡管理員</a></li>
{% endif %}
</ul>
</nav>
<div>
{% if message %}
<div>{{ message }}</div>
{% endif %}
<div>
<h3>登陸我的私人日記</h3>
</div>
<form action="." method="post">
{% csrf_token %}
<label for="user_name">你的姓名:</label>
<input id="user_name" type="text" name="user_name">
<label for="user_color">你喜歡的顏色</label>
<input id="user_color" type="text" name="user_color">
<button type="submit" value="設置">提交</button>
</form>
</div>
</body>
</html>
這個是錯誤的views.py的代碼
from django.shortcuts import render, HttpResponse, redirect, render_to_response
from django.template.loader import get_template
def login(request):
# 如果是POST方法提交
if request.method == 'POST':
# 查看窗體屬性的正確性
username = request.POST['user_name']
usercolor = request.POST['user_color']
message = "登陸成功"
response = render_to_response("login.html", locals())
response.set_cookie('username', username)
response.set_cookie('usercolor', usercolor)
else:
# 這里出的錯
response = render_to_response("login.html")
return response
這個是改正后的views.py代碼
from django.shortcuts import render, HttpResponse, redirect, render_to_response
from django.template.loader import get_template
def login(request):
# 如果是POST方法提交
if request.method == 'POST':
# 查看窗體屬性的正確性
username = request.POST['user_name']
usercolor = request.POST['user_color']
message = "登陸成功"
response = render_to_response("login.html", locals())
response.set_cookie('username', username)
response.set_cookie('usercolor', usercolor)
else:
# 改成render就好了...
response = render(request, "login.html")
return response