【问题标题】:How to import a template tag in the interactive shell?如何在交互式 shell 中导入模板标签?
【发布时间】:2012-08-15 20:52:41
【问题描述】:

如何在交互式 shell 中导入自定义模板标签或过滤器以查看一切是否正常?

我有两台机器的行为不同,我不知道如何进行一些调试。

在生产机器上我无法加载模板过滤器,我收到错误“找不到模板库”。 在本地机器上一切正常。

【问题讨论】:

    标签: django django-templates django-shell


    【解决方案1】:

    如果您担心拼写错误、缺少__init__.py 问题或屏蔽ImportErrors,您可以只导入该函数。假设如下结构:

    foo
    ├── bar
    │   ├── __init__.py
    │   ├── models.py
    │   ├── static
    │   │   └── ..
    │   ├── templates
    │   │   └── ..
    │   ├── templatetags
    │   │   ├── __init__.py
    │   │   └── baz.py
    │   ├── views.py
    ├── manage.py
    └── foo
        ├── __init__.py
        ├── settings.py
        ├── urls.py
        └── wsgi.py
    

    以及baz.py的以下内容:

    from django import template
    
    register = template.Library()
    
    @register.filter
    def capitalize(value):
        return value.capitalize()
    

    你会跑

    >>> from bar.templatetags import baz
    >>> print baz.capitalize('test')
    'test'
    

    【讨论】:

    • 我选择你的作为接受的答案,因为它非常详细。感谢大家的快速解答。
    【解决方案2】:

    像这样导入过滤器:

    from django.template import defaultfilters as filters
    filters.date( date.today() )
    

    您应该导入自定义过滤器,而不是默认过滤器:

    from myApp.templatetags import poll_extras
    poll_extras.cut( 'ello' )
    

    仔细检查您的生产服务器中安装的应用程序的设置。

    【讨论】:

      猜你喜欢
      • 2016-04-05
      • 2020-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-24
      • 2010-09-20
      • 2015-03-28
      相关资源
      最近更新 更多