Django templateTag中的上下文键错误

2024-05-20 10:26:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我的应用程序的templatetag代码对上下文变量中缺少的键(page)抛出KeyError。在我的模板中,我没有使用context.variableKeyName,我只引用variableKeyName(例如{% if is_paginated %})。在我的模板中,我可以引用键page,没有任何异常。在

如何将上下文及其所需的键放入templatetag?在


具体情况如下:

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

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

这段代码叫做: https://bitbucket.org/ubernostrum/django-profiles..

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

^{pr2}$

(我使用的templatetag的灵感来自于为django1.3http://djangosnippets.org/snippets/2680/更新的http://www.tummy.com/.../django-pagination/

但这会导致'paged'的键错误。在


Tags: django代码org模板应用程序httpifis
2条回答

正确的编码方法是:

{% paginator v 3 %}

v-包含db项的变量

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

Required context variables: paged: The Paginator.page() instance.

它还用于模板标记:

paged = context['paged']

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

相关问题 更多 >