Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django can't override form field widget

I need to generate column based checkboxes in my form.

# 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>

and here is my form

    # 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

I added 'django.forms' in my INSTALLED_APPS list, but forms render default CheckboxSelectMultiple template.

Also I read this docs https://docs.djangoproject.com/en/3.0/ref/forms/renderers/#overriding-built-in-widget-templates and tried to put my template to myapp/templates/django/forms/widgets/checkbox_select.html, but had no luck, render default template again. For debugging I set template_name='template_which_not_exist', but still got no errors and render default template. Please help me

like image 589
Сергей Пустовит Avatar asked Dec 20 '25 18:12

Сергей Пустовит


1 Answers

  1. Add 'django.forms' to your INSTALLED_APPS.

  2. Add FORM_RENDERER = 'django.forms.renderers.TemplatesSetting' to your settings.py.

like image 119
aref Avatar answered Dec 23 '25 07:12

aref