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

时间:2022-09-19 20:22:44

报错说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))

这样就解决了