Django目标模板中的单个复选框

时间:2013-06-25 21:54:31

标签: django django-forms django-templates

我有一张表格:

class AccessoriesForm(forms.Form):

    available_accessories = Parts.objects.all()

    accessory = forms.ModelMultipleChoiceField(
        queryset=available_accessories,
        widget=forms.CheckboxSelectMultiple(
            attrs={'class': 'accessory-checkbox'}
        ),
        label=None
    )

在我的模板中:

{% for field in accessory_form %}
    {{ field }}
{% endfor %}

这给了我一个复选框列表。但我希望能够定位单个复选框,以便我可以在每个复选框旁边添加一个唯一的图像。如果我能得到每个字段的名称,那就行了。

我试过了:

{% for field in accessory_form %}
    {{ field }}{{ field.name }}
{% endfor %}

{% for field in accessory_form %}
    {{ field }}{{ field.label }}
{% endfor %}

但这只是给了我这个领域的标签。

任何帮助都非常感激。

2 个答案:

答案 0 :(得分:2)

我建议编写自己的CheckboxSelectMultiple小部件子类来执行此操作,覆盖其render方法。渲染代码非常简单,但是该窗口小部件返回整个<ul>元素,并带有预先渲染的复选框 - 试图拉出模板中各个复选框的表示最多也很棘手。

这样的事情:

class ImageCheckboxSelectMultiple(CheckboxSelectMultiple):

    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))
            # Here's the new part
            image_element = u'<img src="/images/some_image.png">'
            output.append(u'<li>%s<label%s>%s %s</label></li>' % (image_element, label_for, rendered_cb, option_label))
        output.append(u'</ul>')
        return mark_safe(u'\n'.join(output))

根据您的设置,您可能希望将STATIC_URL用作图像路径的一部分。

答案 1 :(得分:0)

完整性,这是我的解决方案:

我在python dict中存储可用附件的必要字段,然后传递给模板中的javascript:

var AccessoryArray = new Array();
{% for accessory in available_accessories %}
    var this_object = new Object();
    this_object.description = "{{ accessory.full_description }}";
    this_object.filename = "{{ accessory.filename }}";
    AccessoryArray[{{ accessory.pk }}] = this_object;
{% endfor %}


$(document).ready(function() {
  // iterate through the accessory checkboxes
  $('input.accessory-checkbox').each(function(){

    // construct output for image and full description
    var filename_output = '<img src="' + media_url + 'parts/' + AccessoryArray[$(this).val()].filename + '" />';
    var description_output = '<span class="accessory-description-text">' + AccessoryArray[$(this).val()].description + '</span>';

    // insert html after the input label
    $(this).parent().after(description_output).after(filename_output);
  });
});