[英]Django custom filter not registering in tag library
我編寫了以下過濾器(在templatetags/custom_errors.py
):
from django import template
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter
def custom_errors(bound_field):
return mark_safe(f'<span id="{bound_field.id_for_label}-error" class="error">{", ".join(bound_field.errors)}</span>' if bound_field.errors else '')
我正嘗試在模板中使用以下代碼:
{% load widget_tweaks %}
{% load custom_errors %}
{% load label_with_classes %}
{% csrf_token %}
<div class="row">
<div class="input-field col s12">
{{ form.session_number|add_error_class:"invalid" }}
{{ form.session_number|custom_errors }}
{{ form.session_number|label_with_classes }}
</div>
</div>
但是,我收到了TemplateSyntaxError
: 'custom_errors' is not a registered tag library
:
但是,令我感到困惑的是,某些注冊的標簽(例如label_with_classes
)是以相同的方式完成的。 這是dashboard/templatetags
的樹狀視圖:
dashboard/templatetags
├── active_page.py
├── custom_errors.py
├── edit_view_family_heading.py
├── google_analytics.py
├── label_with_classes.py
├── order_link.py
├── paginator.py
└── profile_badge.py
表示label_with_classes.py
是在相同的目錄中custom_errors.py
。 以下是label_with_classes.py
的內容:
from django import template
from django.forms import ChoiceField, BooleanField, DateField
from titlecase import titlecase
register = template.Library()
def pretty_name(name):
"""Convert 'first_name' to 'First Name'."""
return titlecase(name.replace('_', ' '))
@register.filter(is_safe=True)
def label_with_classes(bound_field, contents=None):
'''Extend Django's label_tag() method to provide the appropriate Materialize CSS classes'''
# The field should have the 'active' class if it has a value (see http://materializecss.com/forms.html),
# except for ChoiceFields (which include ModelChoiceFields and MultipleChoiceFields) and BooleanFields
should_be_active = (bound_field.value() and not isinstance(bound_field.field, (ChoiceField, BooleanField)))\
or isinstance(bound_field.field, DateField)
active = 'active' if should_be_active else ''
invalid = 'invalid' if bound_field.errors else ''
classes = f"{active} {invalid}".strip()
contents = contents or pretty_name(bound_field.name)
return bound_field.label_tag(
attrs={'class': classes},
contents=contents,
label_suffix='')
我沒有看到兩個過濾器的注冊方式有什么區別(除了一個過濾器具有is_safe=True
,另一個沒有)。 為什么custom_errors
過濾器未注冊? 是否存在某種緩存問題?
我運行python manage.py runserver
的終端以某種方式變得無響應,並且沒有響應Cntrl + C。 我終止了該過程並重新啟動了開發服務器,現在一切正常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.