开发者社区> 问答> 正文

Django防跨站{% csrf_token %}标签?报错

我的代码很简单:

from django.http import HttpResponse
text = """<form method="POST" action="/add/">
    <input type="text" name="a" value="%d"> + <input type="text" name="b" value="%d">
    <input type="submit" value="="> <input type="text" value="%d">
</form>"""

def index(request):
    if request.POST.has_key('a'):
        a = int(request.POST['a'])
        b = int(request.POST['b'])
    else:
        a = 0
        b = 0
    return HttpResponse(text % (a, b, a + b))
提交表格就返回403错误: CSRF verification failed. Request aborted.

网上传说的插入{% csrf_token %},在GET的时候就直接报错:

ValueError at /add/

unsupported format character '}' (0x7d) at index 50

请问各位,我要怎么做?


展开
收起
爱吃鱼的程序员 2020-06-22 21:16:04 466 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB

    暂时找到一种方法:
    屏蔽跨站检测

    fromdjango.views.decorators.csrfimportcsrf_exempt@csrf_exemptdefindex(request):...

    https://docs.djangoproject.com/en/1.4/ref/contrib/csrf/

    看 Howtouseit 

    它上面的第一种方式我试过然后就向我描述的一样,第二种方法是使用模板,但是我用的不是模板要是我读得懂就好了。。。。。发现了 , {%csrf_token%} 在模板里才有作用。但是就像我这样直接写的代码呢?

    最后我还是想通了,用js好了

    <!DOCTYPEhtml><html><body><inputtype="text"id="a"value="0">+<inputtype="text"id="b"value="0"><inputtype="button"onclick=result()value="="><inputtype="text"id="c"value="0"><scripttype="text/javascript">functionresult(){a=document.getElementById('a').value;a=parseFloat(a);b=document.getElementById('b').value;b=parseFloat(b);c=document.getElementById('c');c.value=(a+b)+"";}</script></body></html>

    个哈市打算打

    阿斯达

    D 算

    要不你在模板里用{%csrf_token%},要不你用form造表单,手册上有
    2020-06-22 21:16:22
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载