在使用csrf渲染网页时出现context must be a dict rather than RequestContext

Django版本:2.2
今天在练习窗体的时候使用到了csrf验证,所以views中的函数也要修改,通过 Template 的 render方法调用,但是遇到了context must be a dict rather than RequestContext,事实上有一些资料中已经指出来了,不仅仅是 RequestContext,其实Context也不可以。
这是我出错的代码

from django.template import RequestContext
from django.template.loader import get_template
from django.http import HttpResponse
import os
from myform import models

def post(request):
    tem = get_template('post.html')
    moods = models.Mood.objects.all()
    message = '如果要张贴信息,那么每一个信息都要填写'
    request_context = RequestContext(request, {'moods': moods, 'message': message})
    html = tem.render(request_context)
    # html = tem.render(locals())
    return HttpResponse(html)

这样运行后会出现标题中的错误,查询网上的资料发现根本原因是*django.template.loader.loader.get_template(template_name)*返回的对象并不是 django.template.Template 对象。
##解决方法如下:

from django.shortcuts import render
from django.template import RequestContext
from django.template.loader import get_template
from django.http import HttpResponse
import os
from myform import models
from django.template import Template

    moods = models.Mood.objects.all()
    message = '如果要张贴信息,那么每一个信息都要填写'
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    with open(os.path.join(BASE_DIR, 'templates\post.html'), encoding='utf-8') as fr:
        template_string = fr.read()
     # 不能用get_template方法,必须用原生的read方法
    tem = Template(template_string)
    request_context = RequestContext(request)
    request_context.push(locals())
    return HttpResponse(tem.render(request_context))

这样解决了csrf验证(在网页中也要加入{% csrf_token %})

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值