Django 无法覆盖表单字段小部件

标签 django django-forms django-templates

我需要在我的表单中生成基于列的复选框。

# 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',但仍然没有错误并呈现默认模板。请帮助我

最佳答案

  1. 'django.forms' 添加到您的 INSTALLED_APPS

  2. FORM_RENDERER = 'django.forms.renderers.TemplatesSetting' 添加到您的 settings.py

关于Django 无法覆盖表单字段小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59293917/

相关文章:

django - 如何自定义 Django-allauth 和模板?

django-templates - 上下文值/变量未在blocktrans模板标签内呈现

python - Django - 选择与模型(FK)

python - 多个 Django 模板加载器

python - Django:无法将关键字 '' 解析为字段。选项是:

json - 从 Django 模型获取数据并使用 AJAX 在 html 表中显示

python - Django:ModelMultipleChoiceField 不选择初始选择

Python Django 表单多选 HTML 输出

Django - ModelForm 创建还是更新?

html - 如何在表单字段中保存和显示先前输入的值?