【问题标题】:Django can't override form field widgetDjango 无法覆盖表单字段小部件
【发布时间】:2020-04-05 05:09:45
【问题描述】:

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

# 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 django-forms django-templates


    【解决方案1】:
    1. 将'django.forms' 添加到您的INSTALLED_APPS。

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

    【讨论】:

      猜你喜欢
      • 2011-03-29
      • 1970-01-01
      • 2012-11-27
      • 2011-03-28
      • 2012-04-10
      • 2015-10-06
      • 2020-09-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多