【问题标题】:context KeyError in django templateTagdjango templateTag 中的上下文 KeyError
【发布时间】:2012-07-11 14:46:06
【问题描述】:

我的应用程序的模板标签代码为上下文变量中缺少的键 (page) 引发 KeyError。在我的模板中,我不使用 context.variableKeyName 引用上下文变量,我只是引用 variableKeyName(例如{% if is_paginated %})。在我的模板中,我可以毫无例外地引用密钥page

我应该如何将上下文及其所需的键放入我的模板标签中?


以下是详细信息:

我正在使用 django-profiles 返回一些配置文件的列表:

url(r'^profiles/$', 'profiles.views.profile_list', 
kwargs={ 'paginate_by':10 }, 
name='profiles_profile_detail'),

在这里调用这段代码: https://bitbucket.org/ubernostrum/django-profiles..

在我的模板中,我在调用模板标签之前测试{% if is_paginated %}

{% if is_paginated %}{% load paginator %}{% paginator 3 %}{% endif %}

(我使用的模板标签灵感来自 http://www.tummy.com/.../django-pagination/ 为 django 1.3 http://djangosnippets.org/snippets/2680/ 更新)

但这会导致“分页”的 KeyError。

【问题讨论】:

    标签: python django django-templates


    【解决方案1】:

    http://djangosnippets.org/snippets/2680/ 的文档(类中的 cmets)说:

    必需的上下文变量:paged:Paginator.page() 实例。

    也用在模板标签中:

    paged = context['paged']
    

    您需要提供此上下文变量才能使此模板标签起作用。我认为您最好的选择是复制profiles.views.profile_list 视图的代码并添加此上下文变量。不幸的是,它仍然是一个基于函数的视图 - 否则扩展它会更干净、更容易。

    【讨论】:

    • 谢谢西蒙。我的模板中不是隐含的上下文(因为 page & is_paginated 可以正确引用吗?)。我假设相同的隐式上下文将传递给模板标签。如果我正确理解您的回复,我需要在视图代码中明确设置上下文或分页变量吗?
    【解决方案2】:

    正确的编码方式是:

    {% paginator v 3 %}
    

    v - 包含数据库项的变量

    【讨论】:

      猜你喜欢
      • 2019-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-18
      • 2011-08-28
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      相关资源
      最近更新 更多