除了使用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)在
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号