【问题标题】:Django 1.11 TypeError at / context must be a dict rather than unicode [closed]Django 1.11 TypeError at / context 必须是 dict 而不是 unicode [关闭]
【发布时间】:2018-10-29 13:08:05
【问题描述】:

我使用 Django 1.11 创建网站。当我运行本地主机http://127.0.0.1:8000/ 时,错误“TypeError at / 上下文必须是 dict 而不是 unicode。 “我不知道如何解决它。

违规行:make_context 中的 \venv\lib\site-packages\django\template\context.py,第 287 行

整个视图 context.py 的代码 导入警告 从上下文库导入上下文管理器 从副本导入副本

从 django.utils.deprecation 导入 RemovedInDjango20Warning

硬编码处理器,更容易使用 CSRF 保护。

_builtin_context_processors = ('django.template.context_processors.csrf',)

类 ContextPopException(异常): “pop() 被调用的次数比 push() 多” 通过

类 ContextDict(dict): def init(self, context, *args, **kwargs): super(ContextDict, self).init(*args, **kwargs)

    context.dicts.append(self)
    self.context = context

def __enter__(self):
    return self

def __exit__(self, *args, **kwargs):
    self.context.pop()

类 BaseContext(对象): def init(self, dict_=None): self._reset_dicts(dict_)

def _reset_dicts(self, value=None):
    builtins = {'True': True, 'False': False, 'None': None}
    self.dicts = [builtins]
    if value is not None:
        self.dicts.append(value)

def __copy__(self):
    duplicate = copy(super(BaseContext, self))
    duplicate.dicts = self.dicts[:]
    return duplicate

def __repr__(self):
    return repr(self.dicts)

def __iter__(self):
    for d in reversed(self.dicts):
        yield d

def push(self, *args, **kwargs):
    dicts = []
    for d in args:
        if isinstance(d, BaseContext):
            dicts += d.dicts[1:]
        else:
            dicts.append(d)
    return ContextDict(self, *dicts, **kwargs)

def pop(self):
    if len(self.dicts) == 1:
        raise ContextPopException
    return self.dicts.pop()

def __setitem__(self, key, value):
    "Set a variable in the current context"
    self.dicts[-1][key] = value

def set_upward(self, key, value):
    """
    Set a variable in one of the higher contexts if it exists there,
    otherwise in the current context.
    """
    context = self.dicts[-1]
    for d in reversed(self.dicts):
        if key in d.keys():
            context = d
            break
    context[key] = value

def __getitem__(self, key):
    "Get a variable's value, starting at the current context and going upward"
    for d in reversed(self.dicts):
        if key in d:
            return d[key]
    raise KeyError(key)

def __delitem__(self, key):
    "Delete a variable from the current context"
    del self.dicts[-1][key]

def has_key(self, key):
    warnings.warn(
        "%s.has_key() is deprecated in favor of the 'in' operator." % self.__class__.__name__,
        RemovedInDjango20Warning
    )
    return key in self

def __contains__(self, key):
    for d in self.dicts:
        if key in d:
            return True
    return False

def get(self, key, otherwise=None):
    for d in reversed(self.dicts):
        if key in d:
            return d[key]
    return otherwise

def setdefault(self, key, default=None):
    try:
        return self[key]
    except KeyError:
        self[key] = default
    return default

def new(self, values=None):
    """
    Returns a new context with the same properties, but with only the
    values given in 'values' stored.
    """
    new_context = copy(self)
    new_context._reset_dicts(values)
    return new_context

def flatten(self):
    """
    Returns self.dicts as one dictionary
    """
    flat = {}
    for d in self.dicts:
        flat.update(d)
    return flat

def __eq__(self, other):
    """
    Compares two contexts by comparing theirs 'dicts' attributes.
    """
    if isinstance(other, BaseContext):
        # because dictionaries can be put in different order
        # we have to flatten them like in templates
        return self.flatten() == other.flatten()

    # if it's not comparable return false
    return False

类上下文(BaseContext): “变量上下文的堆栈容器” def init(self, dict_=None, autoescape=True, use_l10n=None, use_tz=None): self.autoescape = 自动转义 self.use_l10n = use_l10n self.use_tz = use_tz self.template_name = "未知" self.render_context = RenderContext() # 设置为原始模板——而不是扩展或包含 # 模板 -- 在渲染期间,请参阅 bind_template。 self.template = 无 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)

类渲染上下文(BaseContext): """ 用于存储模板状态的堆栈容器。

RenderContext simplifies the implementation of template Nodes by providing a
safe place to store state between invocations of a node's `render` method.

The RenderContext also provides scoping rules that are more sensible for
'template local' variables. The render context stack is pushed before each
template is rendered, creating a fresh scope with nothing in it. Name
resolution fails if a variable is not found at the top of the RequestContext
stack. Thus, variables are local to a specific template and don't affect the
rendering of other templates as they would if they were stored in the normal
template context.
"""
template = None

def __iter__(self):
    for d in self.dicts[-1]:
        yield d

def __contains__(self, key):
    return key in self.dicts[-1]

def get(self, key, otherwise=None):
    return self.dicts[-1].get(key, otherwise)

def __getitem__(self, key):
    return self.dicts[-1][key]

@contextmanager
def push_state(self, template, isolated_context=True):
    initial = self.template
    self.template = template
    if isolated_context:
        self.push()
    try:
        yield
    finally:
        self.template = initial
        if isolated_context:
            self.pop()

类请求上下文(上下文): """ template.Context 的这个子类自动使用 引擎配置中定义的处理器。 可以将其他处理器指定为可调用列表 使用“处理器”关键字参数。 """ def init(self,request,dict_=None,processor=None,use_l10n=None,use_tz=None,autoescape=True): super(RequestContext, self).init( dict_, use_l10n=use_l10n, use_tz=use_tz, autoescape=autoescape) self.request = 请求 self._processors = () if processor is None else tuple(processors) self._processors_index = len(self.dicts)

    # placeholder for context processors output
    self.update({})

    # empty dict for any new modifications
    # (so that context processors don't overwrite them)
    self.update({})

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

    self.template = template
    # Set context processors according to the template engine's settings.
    processors = (template.engine.template_context_processors +
                  self._processors)
    updates = {}
    for processor in processors:
        updates.update(processor(self.request))
    self.dicts[self._processors_index] = updates

    try:
        yield
    finally:
        self.template = None
        # Unset context processors.
        self.dicts[self._processors_index] = {}

def new(self, values=None):
    new_context = super(RequestContext, self).new(values)
    # This is for backwards-compatibility: RequestContexts created via
    # Context.new don't include values from context processors.
    if hasattr(new_context, '_processors_index'):
        del new_context._processors_index
    return new_context

def make_context(context, request=None, **kwargs): """ 从普通 dict 和可选的 HttpRequest 创建合适的上下文。 """ 如果 context 不是 None 也不是 isinstance(context, dict): raise TypeError('context 必须是 dict 而不是 %s。' % context.class.name) // 287 如果请求为无: 上下文 = 上下文(上下文,**kwargs) 别的: # 需要以下模式来确保值来自 # context 覆盖来自模板上下文处理器的那些。 original_context = 上下文 context = RequestContext(request, **kwargs) 如果 original_context: context.push(original_context) 返回上下文

【问题讨论】:

  • 发布大量无关紧要的代码——甚至没有正确格式化——也无济于事。而是发布完整的回溯和相关代码(=>您自己的代码,而不是 django 的内部代码)。

标签: python django django-templates


【解决方案1】:

您将上下文传递给模板的位置确保它是字典而不是字符串

【讨论】:

    猜你喜欢
    • 2017-10-02
    • 1970-01-01
    • 2019-07-01
    • 2022-10-13
    • 2022-11-06
    • 1970-01-01
    • 1970-01-01
    • 2016-10-21
    • 1970-01-01
    相关资源
    最近更新 更多