我需要在我的表单中生成基于列的复选框。
# 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',但仍然没有错误并呈现默认模板。请帮助我
最佳答案
将
'django.forms'
添加到您的INSTALLED_APPS
。将
FORM_RENDERER = 'django.forms.renderers.TemplatesSetting'
添加到您的settings.py
。
关于Django 无法覆盖表单字段小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59293917/