Align radio buttons horizontally in django forms

前端 未结 7 1885
借酒劲吻你
借酒劲吻你 2021-02-08 01:50

HI

I want to align the radio buttons horizontally. By default django forms displays in vertical format.

feature_type  = forms.TypedChoiceField(choices =         


        
7条回答
  •  耶瑟儿~
    2021-02-08 02:31

    On my Django 2.2.6 above solutions did not worked well, so I post my solution after many tries and following the breadcrumbs until the django forms widget templates used.

    I had to override 2 templates, and heritage my own widget class and then point it.

    The modified default django templates have been:

    • django/forms/templates/django/forms/widgets/input_option.html
    • django/forms/templates/django/forms/widgets/multiple_input.html

    Now they are:

    PROJECT_NAME/PROJECT_APP/templates/admin/horizontal_option.html

    {% if widget.wrap_label %}{% endif %}{% include "django/forms/widgets/input.html" %}{% if widget.wrap_label %} {{ widget.label }}{% endif %}
    

    PROJECT_NAME/PROJECT_APP/templates/admin/horizontal_radios.html

    {% with id=widget.attrs.id %}{% for group, options, index in widget.optgroups %}{% if group %}
      
  • {{ group }} {% endif %}{% for option in options %} {% include option.template_name with widget=option %}{% endfor %}{% if group %}
{% endif %}{% endfor %} {% endwith %}
  • The first one includes a hardcoded class: class="radio-inline" at labels, which in default Django had nothing
  • The second one the rendering of the set of radios, I removed the extra HTML li tags they were rendered inside the internal ul tag.

Then you need to create your own widget class:

from django.forms import RadioSelect


class HorizontalRadioSelect(RadioSelect):
    template_name = 'admin/horizontal_radios.html'
    option_template_name = 'admin/horizontal_inputs.html'

And finally, in my case, I pointed to it overriding formfield_overrides class attribute in my admin. But you can do this in your models too I think:

    formfield_overrides = {
        models.BooleanField: {'widget': HorizontalRadioSelect(choices=[(True, "Yes"), (False, "No"), (None, "Unknown")],)},
    }

提交回复
热议问题