Python异常:Django2.0.5--context must be a dict rather than Context/RequestContext.

本文介绍了在使用Django进行Web开发时遇到的问题:无法通过Template的render方法使用RequestContext及Context对象。文章提供了两种错误的代码示例,并详细解释了如何解决这些问题,包括使用原生文件读取方法替代。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近用 Python django做 web 开发的时候发现 RequestContext 并不能跟看到的一些资料一样通过 Template 的 render方法调用,事实上有一些资料中已经指出来了,不仅仅是 RequestContext,其实Context也不可以,直接代码通常如下:

t = loader.get_template('context_request.html')
c = RequestContext(request, {'private1': 'self info'}, processors=[custom_proc])
return HttpResponse(t.render(c))

或者使用render_to_response

context = Context({'private1': 'self info'})
return render_to_response('context_request.html', context)

测试就会发现上述两种写法都会抱错,针对第二种,只需要将context用字典代替即可,这个报错时已经说明了解决方案。

但是针对第一种写法,我们需要使用RequestContext来传递重复的参数,因此这个地方不能使用dict,否则就需要传递大量的重复参数,修改方法也很简单,不要调用 Template 的 render 方法,而用原生的读文件的方法,代码如下:

    with open(os.path.join(BASE_DIR, 'company/templates/context_request.html'), 'r') as fr:
        template_string = fr.read()
    # t = loader.get_template('context_request.html')  # 不能用loader.get_template方法,必须用原生的read方法
    t = Template(template_string)
    c = RequestContext(request, {'private1': 'self info'}, processors=[custom_proc])
    # c = {'private1': 'self info'}
    return HttpResponse(t.render(c))
    # return render_to_response('context_request.html', {'private1': 'self info'},
    #                           context_instance=RequestContext(request, processors=[custom_proc]))

那么这个时候就是可以使用的。

根本原因:loader.get_template(template_name)返回的对象并不是 django.template.Template 对象。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值