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

时间:2013-09-03 12:17:41

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

forms.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

views.py

def types(method):
    """"""""""""
    types = TypeSelectionForm(type_id)
    return render(request,'types.html',{'types':types})

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

types.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>

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

需要帮助。

4 个答案:

答案 0 :(得分:4)

为什么不使用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)

将其放入模板标签中,然后只在模板

中执行此操作
{% load ad_div %}

{# some Code #}

{{ form|as_div }}

{# some other code #} 

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

其他方法(Better Cleaner)

另一种方法是扩展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 }} 

答案 1 :(得分:1)

来自documentation

  

Django 1.4中的新内容。

     

为了更精细地控制生成的标记,您可以循环   模板中的单选按钮。假设表格myform带有   使用beatles作为其窗口小部件的字段RadioSelect

{% 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 %}

您还应该使用ModelMultipleChoiceField

class TypeSelectionForm(forms.Form):
    checkbox_field = forms.ModelMultipleChoiceField(label="",
                                                    queryset=Types.objects.none(),
                                                    required=False)

    def __init__(self, *args, **kwargs):
        qs = kwargs.pop('queryset')
        super(TypeSelectionForm, self).__init__(*args, **kwargs)
        self.fields['checkbox_field'].queryset = qs

从您的观点中启动它:

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 :(得分:1)

窗口小部件采用attrs属性,该属性应将属性添加到每个输入。试试这个:

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

<强>更新

所以看起来上面提到的粒度方法仅适用于单选按钮小部件。但你想要的实际上非常简单。只需正常输出复选框:

{% for field in types.checkbox_field %}                                 
 {{field}}
{% endfor %}

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

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

}

<强>更新

如果要以不同方式呈现复选框,则需要自定义窗口小部件类,因为这是窗口小部件作业。这样的事情会让你前进。我个人使用小部件上的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)

答案 3 :(得分:0)

这与@bhappy的解决方案类似。整体解决方案是定义自定义as_div方法,并将其用作模板中的模板过滤器。看看这个django片段帖子:Custom Form Example: Forms for Bootstrap Html - CSS Toolkit