加载自定义模板标签时出现问题(错误:没有名为x的模块) [英] Problem loading custom template tags (Error: No module named x)

查看:268
本文介绍了加载自定义模板标签时出现问题(错误:没有名为x的模块)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在编写一些自定义模板标签,但是由于某些原因它们将无法加载。我的目录结构如下:

I am currently writing a few custom template tags but for some reason they will not load. My directory structure is as follows:

MyProj
 |
 ----MyApp
     |
     |----templatetags
          |
          |----myapp_tags.py
          |----__init__.py

在myapp_tags.py

from django.template import Library, Node
from myproj.myapp.models import Product

register = Library()

class LatestProductsNode(Node):
    def render(self, context):
        context['recent_products'] = Product.objects.all()[:5]
        return ''

def get_latest_products(parser, token):
    return LatestProductsNode()

get_latest_products = register.tag(get_latest_products)

在设置中.py

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.admin',
    'myproj.myapp',
)

在模板中

{% load myapp_tags %}

尝试加载页面时遇到的错误:

Exception Type:     TemplateSyntaxError Exception Value:    

'myapp_tags' is not a valid tag library: Could not load template library from django.templatetags.myapp_tags, No module named myapp_tags


推荐答案

settings.py 中,永远不要明确命名项目 myproj。在 INSTALLED_APPS 中,只需使用 myapp即可。另外,您应该具有以下内容:

in settings.py, you should never name the project 'myproj' explicitely. In INSTALLED_APPS, just use 'myapp'. Also, you should have this :

TEMPLATE_LOADERS = (
    'django.template.loaders.app_directories.load_template_source',
)

并确保使用 __ init __。py myapp 文件夹以及 templatetags 文件夹中。

And be sure to have an __init__.py in the myapp folder as well as in templatetags.

使用 manage.py shell ,然后从myapp.templatetags 导入myapp_tags 来查找是否存在 myapp_tags.py 文件中的任何python错误。

Use manage.py shell then from myapp.templatetags import myapp_tags to find out if theres any python error in the myapp_tags.py file.

此外,请确保 myapp_tags.py 文件名不与项目中的另一个文件夹/文件冲突。

Also, be sure that myapp_tags.py file name doesnt conflicts with another folder/file in your project.

希望这会有所帮助。

这篇关于加载自定义模板标签时出现问题(错误:没有名为x的模块)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆