Djangoで発生した問題(1)TypeError:context must be a dict rather than Context.


1 . TypeError: context must be a dict rather than Context.
翻訳:コンテキストは、ContextインスタンスオブジェクトDjangoバージョン1.11でエラーが報告されたコードがviewsから来るのではなく、フィールドである必要があります.py:
def current_datetime(request):
     now = datetime.datetime.now()
     t = get_template("ctime.html") ##get_template()          Template   
     ctx = Context({'now':now})
     html = t.render(ctx) #render    ctx       
     return HttpResponse(html)

エラーメッセージ:Traceback(most recent call last):File"D:python 3.6libsite-packagesdjangocorehandlersexception.py"、line 41,in inner response=get_response(request) File “D:\python3.6\lib\site-packages\django\core\handlers\base.py”, line 187, in _get_response response = self.process_exception_by_middleware(e, request) File “D:\python3.6\lib\site-packages\django\core\handlers\base.py”, line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File “E:\python_workspace\sfweb\sfweb\books\views.py”, line 18, in current_datetime html = t.render(ctx) File “D:\python3.6\lib\site-packages\django\template\backends\django.py”, line 64, in render context = make_context(context, request, autoescape=self.backend.engine.autoescape) File “D:\python3.6\lib\site-packages\django\template\context.py”, line 287, in make_context raise TypeError(‘context must be a dict rather than %s.’ % context.class.name) TypeError: context must be a dict rather than Context.
エラーの原因:コードはdjango book 2.0から来て、本は間違いを犯すべきではないと言ってstackoverflowの中から知っていて、問題はバージョンの上で本書はdjango 1.1に基づいて、本機は最新のdjango 1.11バージョンをインストールします
点開D:python 3.6\lib\site-packages\django\template\backends\django.py django 1.11ソースコードから分析します.
class Template(object):

    def __init__(self, template, backend):
        self.template = template
        self.backend = backend

    @property
    def origin(self):
        return self.template.origin

    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)
context = make_context(context, request, autoescape=self.backend.engine.autoescape)から,renderメソッドが伝達するcontextパラメータがmake_context()メソッドでは、make_を見てみましょう.context()メソッドのソースコード:注意:ここのTemplateはdjangoではありません.template.Template,パラメータtemplateはdjangoであるべきである.template.Templateの例
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

if context is not None and not isinstance(context,dict)から、パラメータのcontext()は辞書タイプでなければならないと判断できます(ここでは、Template.render()のcontextパラメータがなぜ辞書でなければならないのかを決定できます)、make_context()は、ContextまたはベースサブクラスRequestContextインスタンスオブジェクトを返します.
上のrender()に戻ります.Templateに戻ります.template.レンダー(Context)は私たちがよく知っているdjangoに戻った.template.Template.render(Context)
正しいコード:
def current_datetime(request):
     now = datetime.datetime.now()
     t = get_template("ctime.html") ##get_template()          Template   ,      django.template.Template  
     #ctx = Context({'now':now})
     html = t.render({'now':now})
     return HttpResponse(html)

フロントは正常!!!