表单.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
View .py
def types(method):
""""""""""""
types = TypeSelectionForm(type_id)
return render(request,'types.html',{'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">
标记
需要帮助。
最佳答案
为什么不使用 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 }}
关于python - 如何添加 <div> 标签而不是 <li>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18592136/