是否可以在templatetags中添加带变量的按钮

时间:2013-09-09 10:06:35

标签: python django python-2.7 django-models django-templates

templatetags.py

from django import template
from django.utils.safestring import mark_safe

register = template.Library()

@register.filter("as_span")

def as_span(ZergitForm):
    ZergitForm_as_span = ZergitForm.as_ul().replace("<ul", "<span").replace("</ul", "</span")
    ZergitForm_as_span = ZergitForm_as_span.replace("<li", "<span").replace("</li", "</span")
    return mark_safe(ZergitForm_as_span)

我正在使用MultipleChoiceField。使用此模板标签后,它将以跨度而不是<li>标签打印表单数据。我想对span中的每个数据执行删除操作。现在它正在打印每个{单个<li>标记中的{1}}值。我需要为每个范围插入一个输入按钮。

是否可以使用templatetag概念。

由于

2 个答案:

答案 0 :(得分:0)

渲染字段而不是整个表单时,您可以执行类似的操作。

如果你构建一个模板标签来渲染一个字段,你可以使用它的id,你需要通过ajax调用来删除它。

答案 1 :(得分:0)

最好更换这些字段的小部件。您好像使用CheckboxSelectMultiple,它使用<ul><li>。创建一个从CheckboxSelectMultiple开始的类并替换其render()方法:

(来自django / forms / widgets.py)

class CheckboxSelectMultiple(SelectMultiple):
    def render(self, name, value, attrs=None, choices=()):
        if value is None: value = []
        has_id = attrs and 'id' in attrs
        final_attrs = self.build_attrs(attrs, name=name)
        output = [u'<ul>']
        # Normalize to strings
        str_values = set([force_unicode(v) for v in value])
        for i, (option_value, option_label) in enumerate(chain(self.choices, choices)):
            # If an ID attribute was given, add a numeric index as a suffix,
            # so that the checkboxes don't all have the same ID attribute.
            if has_id:
                final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i))
                label_for = u' for="%s"' % final_attrs['id']
            else:
                label_for = ''

            cb = CheckboxInput(final_attrs, check_test=lambda value: value in str_values)
            option_value = force_unicode(option_value)
            rendered_cb = cb.render(name, option_value)
            option_label = conditional_escape(force_unicode(option_label))
            output.append(u'<li><label%s>%s %s</label></li>' % (label_for, rendered_cb, option_label))
        output.append(u'</ul>')
        return mark_safe(u'\n'.join(output))
相关问题