Как я могу загрузить пользовательские теги Django из файла?
У меня есть определение тега для mytag в файле mytag.py. Это прекрасно работает, когда я использую проект Django с settings.py и INSTALLED_APPS - я добавляю myapp в список и помещаю mytag.py в myapp/templatetags.
Сейчас я использую django.conf.settings.configure и у меня нет модуля с подкаталогом templatetags - как мне загрузить mytag.py?
Обновить:
Теперь я попытался использовать модуль с каталогом templatetags, но не могу заставить его работать. Вот мои настройки:
файлы:
- MyApp
__init.py__
- templatetags
__init__.py
- mytag.py
- программа
- test.py
- test.html
Это соответствующий код:
# test.py
from django.template import Template, Context
from django.conf import settings
from mostlystatic.processors.mostlystaticprocessor import MostlystaticProcessor
from mostlystatic.stuff import DebugLogger
import sys
sys.path.append("~/")
settings.configure(
DEBUG=True,
TEMPLATE_DEBUG = True,
INSTALLED_APPS = ("myapp",)
)
t = Template(open("test.html").read())
c = Context({})
content = t.render(c)
print content
# test.html
{% load mytag %}
# mytag.py (doesn't load)
from classytags.arguments import Argument
from classytags.core import Tag, Options
from django import template
register = template.Library()
class MyTag(Tag):
name="mytag"
def render_tag(self, context:
return "test"
register.tag(MyTag)
Когда я запускаю test.py, я получаю это сообщение:
Traceback (most recent call last):
File "test.py", line 16, in <module>
t = Template(open("test.html").read())
File "/Library/Python/2.7/site-packages/django/template/base.py", line 125, in __init__
self.nodelist = compile_string(template_string, origin)
File "/Library/Python/2.7/site-packages/django/template/base.py", line 153, in compile_string
return parser.parse()
File "/Library/Python/2.7/site-packages/django/template/base.py", line 270, in parse
compiled_result = compile_func(self, token)
File "/Library/Python/2.7/site-packages/django/template/defaulttags.py", line 1033, in load
(taglib, e))
django.template.base.TemplateSyntaxError: 'mytag' is not a valid tag library: Template library mytag not found, tried django.templatetags.mytag
1 ответ
Самое простое, что нужно сделать, это сделать модуль с templatetags
подкаталог, и включить этот модуль в INSTALLED_APPS
когда вы настраиваете настройки.
Любой другой подход предполагает борьбу с внутренностями Джанго.
Если ваш скрипт не работает, попробуйте разобрать его до чего-то очень простого, как показано ниже, а затем соберите его обратно.
from django.conf import settings
settings.configure(INSTALLED_APPS=('my_app',))
from django.template import Template
# my_tags does not exist, but the error shows that it is
# searching my_app's template tag directory
Template.render("{% load my_tags %}")
TemplateSyntaxError: 'my_tags' is not a valid tag library: Template library my_tags not found, tried django.templatetags.my_tags, my_app.templatetags.my_tags