除了使用Django内置表单,有时往往我们需要自定义表单。对于自定义表单Post方式提交往往会带来由CSRF(跨站请求伪造)产生的错误"CSRF verification failed. Request aborted."
本篇文章主要针对"表单提交"和"Ajax提交"两种方式来解决CSRF带来的错误
一、表单提交
Template:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>计算数字和</title>
</head>
<body>
<form method="post" action="{%url 'Calculate' %}">
{% csrf_token %}
<label for="A"><input id="A" name="ValueA" type="text"></label>
<label for="B"><input id="B" name="ValueB" type="text"></label>
<input type="submit" value="开始计算">
</form>
</body>
</html>
Views.py:
def Calculate(request):
if request.POST:
a=request.POST["ValueA"]
b=request.POST["ValueB"]
c=str(int(a)+int(b))
return render_to_response('Result.html',{'result':c})
else:
return render_to_response('Calculation.html',context_instance=RequestContext(request))
需要注意:
(1)在
Copyright© 2013-2020
All Rights Reserved 京ICP备2023019179号-8