render() must be called with a dict, not a Context. return HttpResponse(t.render(c))解决

报错说render()只能传入字典

错误的代码:

def index(request):
    t=loader.get_template("index.html")
    title={"title":"hello Django"}
    user={"name":"LCY","age":"20"}
    context=Context({"title":title,"user":user})
    return HttpResponse(t.render(context))
   

报错定位在return HttpResponse(t.render(context))

后来查看了下Context的原码是这样写的、

class Context(BaseContext):
    "A stack container for variable context"
    def __init__(self, dict_=None, autoescape=True, use_l10n=None, use_tz=None):
        self.autoescape = autoescape
        self.use_l10n = use_l10n
        self.use_tz = use_tz
        self.template_name = "unknown"
        self.render_context = RenderContext()
        # Set to the original template -- as opposed to extended or included
        # templates -- during rendering, see bind_template.
        self.template = None
        super(Context, self).__init__(dict_)

    @contextmanager
    def bind_template(self, template):
        if self.template is not None:
            raise RuntimeError("Context is already bound to a template")
        self.template = template
        try:
            yield
        finally:
            self.template = None

    def __copy__(self):
        duplicate = super(Context, self).__copy__()
        duplicate.render_context = copy(self.render_context)
        return duplicate

    def update(self, other_dict):
        "Pushes other_dict to the stack of dictionaries in the Context"
        if not hasattr(other_dict, '__getitem__'):
            raise TypeError('other_dict must be a mapping (dictionary-like) object.')
        if isinstance(other_dict, BaseContext):
            other_dict = other_dict.dicts[1:].pop()
        return ContextDict(self, other_dict)


从原码中可以看到,当直接使用Context()的时候传入的值无法返回dict,调用update()方法就可以所以根据以上思路修改后为:

def index(request):
    t=loader.get_template("index.html")
    title={"title":"hello Django"}
    user={"name":"LCY","age":"20"}
    context=Context().update({"title":title,"user":user})
    return HttpResponse(t.render(context))

这样就解决了









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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值