django中的csrf与后台模块处理

来源:互联网 发布:淘宝如何绑定银行卡 编辑:程序博客网 时间:2024/06/01 19:19

在表单中使用post方法提交表单数据,需要使用csrf标签,这是Django提供的防止伪装提交请求的功能。get方法提交数据不用使用csrf

用法:

模板中:

<form action="/query" method="post">
    {% csrf_token %}
    <input type="text" name="productname">
    <input type="submit" value="查询">
</form>

模块中:

def query(request):
   
    if request.POST.has_key("productname"):
        products = Product.objects.filter(name = request.POST["productname"])
    else:
        products = Product.objects.all()
   
    pagenum = 1
    if request.GET.has_key("pid"):
        pagenum = request.GET['pid']
    p = Paginator(products,2)  
    page = p.page(pagenum)    
    return render_to_response("index.html",{"user":request.user,"p":p,"page":page},context_instance = RequestContext(request))


然而,在模块处理环节,使用render_to_response返回数据时总是报错csrf验证失败根据网上查找原因如下:


网上原文:


The context_instance parameter in render_to_response wasdeprecated in Django 1.8, and removed in Django 1.10.

The solution is to switch to the render shortcut, which automatically uses a RequestContext.

Update your imports and view as follows. Note that render takes therequest object as its first argument.

from django.shortcuts import renderdef my_view(request):    context = {'foo': 'bar'}    return render(request, 'my_template.html', context)
在1.10版本的django中已经移除了context_instance参数,而我使用的是1.11版本
方法是换用render方法返回数据:
return render(request,"index.html",{"user":request.user,"p":p,"page":page})
简单快捷。
原创粉丝点击