[英]Django Forms: styling forms (checkboxes) manually - Input to be outside of label
我需要在html模板中以以下格式呈现复选框form fields
:
<input id="tag" type="checkbox" name="check" value="1">
<label for="tag">Tag 1</label>
目前,在我的模板中,我尝试:
{{ filter.form.tags.errors }}
{% for field in filter.form.tags %}
<input id="{{ field.id_for_label }}" type="checkbox" name="check">
<label for="{{ field.id_for_label }}">{{ field.value }}</label>
{% endfor %}
这将不会呈现{{ field.value }}
(我得到的是空的而不是Tag 1),并且也不发粘。
我也尝试过:
{% for field in filter.form.tags %}
{{ field.label_tag }}
{{ field }}
{% endfor %}
这使我嵌套了<label><input></input></label>
,但显示了我需要的一切。
是否可以渲染表格以获得我想要的格式? (还应保留checked
例如使刻度线变粘)。
编辑:
class TaskFilter(django_filters.FilterSet):
"""Filter for books by author"""
tags = django_filters.ModelMultipleChoiceFilter(widget=forms.CheckboxSelectMultiple, queryset=Task.tags.most_common())
title = django_filters.CharFilter(field_name='title', lookup_expr='icontains')
class Meta:
model = Task
fields = ['tags', 'title']
views.py
def task_list_filter(request):
if request.method == 'GET':
form = AdditionalForm(request.GET)
# process the form
results = Task.objects.all().order_by('-created')
f = TaskFilter(request.GET, queryset=results)
# Output final query set
results = f.qs[0:100] # only get first 100 objects
# Create pagination
# Get the view
return render(request, 'base/task_list_filter.html', {'filter': f,
'task_list': results,
'form': form })
为了确保复选框处于正确状态,您可以使用自己提供的示例进行一些更改:
{% for field in filter.form.tags %}
<input type="checkbox" id="{{ field.id_for_label }}"
name="{{ field.html_name }}"
{% if field.value %}checked{% endif %}>
<label for="{{ field.id_for_label }}">{{ field.value }}</label>
{% endfor %}
请记住,您可以使用{{ field.label_tag }}
生成整个标签HTML标签。
在HTML中
{% for field in filter.form.tags %}
{{ field.tag }} <!-- Generates the checkbox for the field -->
{{ field.choice_label }} <!-- Generates the named label of the field -->
{% endfor %}
我从这个人那里学到了很多关于Django使用的有用信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.