django - 模板标签 'add' 需要 2 个参数,其中 1 个已提供

标签 django django-templates django-widget-tweaks

我以前使用过 add 但这次出现了这个奇怪的错误:

django.template.exceptions.TemplateSyntaxError: add requires 2 arguments, 1 provided

使用以下代码:

{% render_field form.full_name type="hidden" class="form-control" \
   value=user.first_name|add:"something" %}

但是,如果我将 add 移动到 with,我不会收到错误消息:

{% with fullname=user.first_name|add:"something"%}
   {% render_field form.full_name type="hidden" class="form-control" \
      value=fullname %}
{% endwith %}

最佳答案

所以看起来您正在使用 https://github.com/jazzband/django-widget-tweaks/ 中的 render_field 模板标签

render_field 被实现为 Advanced Custom Tag这是由包维护者实现的,遗憾的是它的参数列表中不支持过滤器。

A simple_taginclusion_tag另一方面;由 Django 定义;确实支持其参数列表中的其他过滤器。

我的意思是说,如果它是 simple_taginclusion_tag,这将起作用 {% my_tag 123 "abcd"book.title warning=message|lower profile=user.profile %}

但是,如果 my_tag 被注册为高级自定义标签;在参数中支持过滤器取决于实现。

正如我从 render_field 代码的实现中看到的那样;这是一个高级自定义标签,过滤器支持似乎已损坏:

@register.tag
def render_field(parser, token):
    """
    Render a form field using given attribute-value pairs

    Takes form field as first argument and list of attribute-value pairs for
    all other arguments.  Attribute-value pairs should be in the form of
    attribute=value or attribute="a value" for assignment and attribute+=value
    or attribute+="value" for appending.
    """
    error_msg = '%r tag requires a form field followed by a list of attributes and values in the form attr="value"' % token.split_contents()[0]
    try:
        bits = token.split_contents()
        tag_name = bits[0]
        form_field = bits[1]
        attr_list = bits[2:]
    except ValueError:
        raise TemplateSyntaxError(error_msg)

    form_field = parser.compile_filter(form_field)

    set_attrs = []
    append_attrs = []
    for pair in attr_list:
        match = ATTRIBUTE_RE.match(pair)
        if not match:
            raise TemplateSyntaxError(error_msg + ": %s" % pair)
        dct = match.groupdict()
        attr, sign, value = \
            dct['attr'], dct['sign'], parser.compile_filter(dct['value'])
        if sign == "=":
            set_attrs.append((attr, value))
        else:
            append_attrs.append((attr, value))

    return FieldAttributeNode(form_field, set_attrs, append_attrs)

具体来说; key=value 对存储在代码中的 attr_list 中,并针对 ATTRIBUTE_RE 正则表达式匹配运行

然后使用 parser.compile_filter(dct['value']) 运行过滤器,但是 dct['value']'user.first_name |add:"' -> 文本 "something" 在这里丢失了。我的猜测是 ATTRIBUTE_RE 正则表达式需要改进以支持它。

>>> ATTRIBUTE_RE.match('value=user.first_name|add:"something"')
<_sre.SRE_Match object at 0x7f8617f5a160>
>>> match.groupdict()
{'attr': 'value', 'value': 'user.first_name|add:"', 'sign': '='}

如您所见,值键已损坏并且缺少您提供的全文;这打破了下游的添加过滤器。

这正是 with 标签要解决的用例;因为它将过滤过程抽象到更高的级别;您可以很好地将新变量传递给您的自定义 render_field 标记。

引用资料:

How to use a template filter on a custom template tag?

https://docs.djangoproject.com/en/2.0/howto/custom-template-tags/#advanced-custom-template-tags

关于django - 模板标签 'add' 需要 2 个参数,其中 1 个已提供,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50172384/

相关文章:

javascript - 在 Jquery 中定义 Django 上下文变量给我错误?

python - DJango filter_queryset

django - 小部件调整错误 ModuleNotFoundError : No module named 'widget_tweaks' with Django forms

django - 如何将 "Add Another"链接按钮内联移动到顶部 Django Admin

django 为所有领域应用小部件

python - 将样式表与 django-widget-tweaks 一起使用?

Django + Influxdb

python - "safe"python HTML 文本格式(ala textile)

django - 如何在 Django 中显示不同时区的所有日期时间对象

python - Django strip_tags 模板过滤添加空格