django中的csrf与后台模块处理

在表单中使用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 render

def 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})
简单快捷。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值