我需要在表单中生成基于列的复选框。
# myapp/templates/forms/widgets/custom.html
<div class="row">
{% for group, options, index in widget.optgroups %}
{% for option in options %}
<div class="col-md-3">
{% include option.template_name with widget=option %}
</div>
{% endfor %}
{% endfor %}
</div>
这是我的表格
# myapp/forms.py
class CustomCheckboxSelectMultiple(forms.CheckboxSelectMultiple):
template_name = 'forms/widgets/custom.html'
class HomePageContactForm(forms.Form):
...
other fields
...
services = forms.ModelMultipleChoiceField(
queryset=Service.objects.all(),
widget=CustomCheckboxSelectMultiple(),
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper = FormHelper(self)
self.helper.form_show_labels = False
我在INSTALLED_APPS列表中添加了“ django.forms”,但表单呈现了默认的CheckboxSelectMultiple模板。
我也阅读了这份文档https://docs.djangoproject.com/en/3.0/ref/forms/renderers/#overriding-built-in-widget-templates 并尝试将我的模板放入myapp / templates / django / forms / widgets / checkbox_select.html,但没有运气,请再次渲染默认模板。为了调试,我设置了template_name ='template_which_not_exist',但仍然没有错误并呈现默认模板。请帮助我