zoukankan      html  css  js  c++  java
  • Django context must be a dict ranther than Context

    1.1

    错误描述

    TypeError at /time/
    context must be a dict rather than Context.
    Request Method:	GET
    Request URL:	http://127.0.0.1:8000/time/
    Django Version:	2.0.5
    Exception Type:	TypeError
    Exception Value:	
    context must be a dict rather than Context.
    Exception Location:	E:Pythondjonevenvlibsite-packagesdjango	emplatecontext.py in make_context, line 274
    Python Executable:	E:PythondjonevenvScriptspython.exe
    Python Version:	3.6.5
    Python Path:	
    ['E:\Python\djone\mysite',
     'E:\Python\djone\venv\Scripts\python36.zip',
     'C:\Users\daixiyu\AppData\Local\Programs\Python\Python36\DLLs',
     'C:\Users\daixiyu\AppData\Local\Programs\Python\Python36\lib',
     'C:\Users\daixiyu\AppData\Local\Programs\Python\Python36',
     'E:\Python\djone\venv',
     'E:\Python\djone\venv\lib\site-packages',
     'E:\Python\djone\venv\lib\site-packages\setuptools-28.8.0-py3.6.egg',
     'E:\Python\djone\venv\lib\site-packages\pip-9.0.1-py3.6.egg']
    Server time:	Fri, 25 May 2018 23:27:35 +0000
    

    代码

    def current_datetime(request):
    	now = datetime.datetime.now()
    	t = get_template('current_datetime.html')
    	html = t.render(Context({'current_date': now}))
    return HttpResponse(html)
    

    分析

    问题出在 t.render() 上 在Django2.0.5中

    get_template()返回的Template对象的render方法上,让我们看一下render方法的源码

    def render(self, context=None, request=None):
        context=make_context(context,request,autoescape=self.backend.engine.autoescape)
        try:
            return self.template.render(context)
        except TemplateDoesNotExist as exc:
            reraise(exc, self.backend)
    

    看第二行,调用了make_context(), 再看 make_context() 的源码

    def make_context(context, request=None, **kwargs):
        """
        Create a suitable Context from a plain dict and optionally an HttpRequest.
        """
        if context is not None and not isinstance(context, dict):
            raise TypeError('context must be a dict rather than %s.' % context.__class__.__name__)
        if request is None:
            context = Context(context, **kwargs)
        else:
            # The following pattern is required to ensure values from
            # context override those from template context processors.
            original_context = context
            context = RequestContext(request, **kwargs)
            if original_context:
                context.push(original_context)
        return context
    

    看到第五行,此时会检查context是否为一个字典,目的是在随后为了使用context创建一个Context实例

    结论

    不要给Template对象的render()方法传递Context对象,其会使用传入的字典,自动创建一个Context对象,以供使用

  • 相关阅读:
    java学习之实例变量初始化
    rip中的连续子网以及不连续子网
    扫描工具
    WScript.SendKeys()的sendkeys发送组合键以及特殊字符
    sql 查询包含字符的数量统计
    leetcode题1Two sum 练习
    vs 2015密钥
    前端 边界圆角
    前端 字体样式
    前端 高级选择器 伪类选择器
  • 原文地址:https://www.cnblogs.com/xiyu714/p/9091619.html
Copyright © 2011-2022 走看看