如何添加<div>标记而不是<li>

2024-03-29 00:36:33 发布

您现在位置:Python中文网/ 问答频道 /正文

在表单.py在

class TypeSelectionForm(forms.Form):
    checkbox_field = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(), label="", required=False)

def __init__(self, type_id, *args, **kwargs):
    super(TypeSelectionForm, self).__init__(*args, **kwargs)

    _type_checkbox = self.fields['checkbox_field']       
    MY_CHOICES=((type.id, type.title) for type in type)
    _type_checkbox.choices = MY_CHOICES
    initial_val = []
    type_selection = Types.objects.filter(parent_type_id=type_id,is_active=True)
    for type_selection in type_selection:
        initial_val.append(type_selection.id)
    _type_checkbox.initial = initial_val

在视图.py在

^{pr2}$

在模板中,我像这样渲染字段

在类型.html在

    {% for field in types.checkbox_field %}                                 
     <div class="deletelist">
     {{field}}<br />
    </div>
   {% endfor %}

它正在生成这样的html

<ul>
<li><label for="id_checkbox_field_0"><input checked="checked" type="checkbox" name="checkbox_field" value="597" id="id_checkbox_field_0" /> comp lab</label></li>
<li><label for="id_checkbox_field_1"><input checked="checked" type="checkbox" name="checkbox_field" value="598" id="id_checkbox_field_1" /> phy lab</label></li>
<li><label for="id_checkbox_field_2"><input checked="checked" type="checkbox" name="checkbox_field" value="599" id="id_checkbox_field_2" /> chem lab</label></li>
</ul>

我想用<div class="class-name">替换<ul><li>标记

需要帮助。在


Tags: nameinselfidfieldfortypeforms
1条回答
网友
1楼 · 发布于 2024-03-29 00:36:33

documentation

New in Django 1.4.

For more granular control over the generated markup, you can loop over the radio buttons in the template. Assuming a form myform with a field beatles that uses a RadioSelect as its widget:

{% for radio in myform.beatles %}
<div class="myradio">
    {{ radio }}
</div>
{% endfor %}

在模板中,应具有以下内容:

{% for radio in types.checkbox_field %}
   <input style="margin: 8px -3px;float: left;" type="button" class="delete_types" id="delete_name"/>{{ radio }}
{% endfor %}

您还应该使用^{}

^{pr2}$

从你的角度出发:

def types(method):
    """"""""""""
    qs = Types.objects.filter(parent_type_id=type_id,is_active=True)
    types = TypeSelectionForm(queryset=qs)
    return render(request,'types.html',{'types':'types'})
网友
2楼 · 发布于 2024-03-29 00:36:33

为什么不使用Django模板标记的功能呢?在

from django import template
from django.utils.safestring import mark_safe
register = template.Library()


@register.filter("as_div")
def as_div(form):
    form_as_div = form.as_ul().replace("<ul", "<div").replace("</ul", "</div")
    form_as_div = form_as_div.replace("<li", "<div").replace("</li", "</div")
    return mark_safe(form_as_div)

把它放在一个模板标签中,然后在你的模板中简单地做这个

^{pr2}$

===============================

其他方法(更干净)

另一种方法是扩展django表单模型

具体如下:

from django.forms.forms import BaseForm

Class AsDiv(BaseForm):

def as_div(self):
        return self._html_output(
            normal_row = u'<div%(html_class_attr)s>%(errors)s%(label)s %(field)s%(help_text)s</div>',
            error_row = u'<div>%s</div>',
            row_ender = '</div>',
            help_text_html = u' <span class="helptext">%s</span>',
            errors_on_separate_row = False)

那你就可以做这是你的模板

{{ form.as_div }} 
网友
3楼 · 发布于 2024-03-29 00:36:33

小部件接受attrs属性,该属性应将该属性添加到每个输入。试试这个:

checkbox_field = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(attrs={'class': 'my-image-class', }), label="", required=False)

更新:

因此,上面提到的粒度方法似乎只适用于单选按钮小部件。但你想要的其实很简单。只需正常输出复选框:

^{pr2}$

这将根据需要输出复选框列表。然后只需使用一点CSS来设置每个列表项的背景图像的样式:

form ul li {
background:url("<my-image>") no-repeat center;
width:20px;
height:20px;

}

更新

如果你想以不同的方式呈现复选框,你需要一个自定义的widget类,因为这是widgets的工作。像这样的事情会让你走的。我个人会使用widget上的attrs选项来添加一个类,但我在这里硬编码了它,以向您展示您的请求是可能的,只是不太好:

class CheckboxDivSelectMultiple(CheckboxSelectMultiple):
'''renders the checkboxes as divs with a hard coded class'''

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'<div>']
    # 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'<div class="%s"><label%s>%s %s</label></div>' % ('new-class', label_for, rendered_cb, option_label))
    output.append(u'</div>')
    return mark_safe(u'\n'.join(output))

在您的表单中使用:

checkbox_field = forms.MultipleChoiceField(widget=forms.CheckboxDivSelectMultiple(), label="", required=False)

相关问题 更多 >