Search code examples
django-formsmany-to-manydjango-crispy-formsdjango-widgettwitter-bootstrap-form

django-crispy-forms bootstrap 4: How to display checkboxes horizontally?


I can't seem to make my CheckboxSelectMultiple widget to display horizontally using django-crispy-forms/bootstrap4.

I've tried : Specifying it on the form's widgets : widgets = {'my_field': forms.CheckboxSelectMultiple(attrs={'class': 'form-check-inline'}),}

but the checkboxes still display vertically, and the template renders to this:

<div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" name="my_field" id="id_my_field_2" value="2" class="form-check-inline"> <label class="custom-control-label" for="id_my_field_2">

This " class="form-check-inline" " is displayed in red.

Same thing happens if I use crispy-forms' helper. self.helper.layout = Layout(Field('my_field', css_class="form-check-inline"))

Any clue why that is? Can someone suggest an alternative?

p.s. : Settings are : CRISPY_TEMPLATE_PACK = "bootstrap4" Template is : {% csrf_token %} {% load crispy_forms_tags %} {% crispy form form.helper %}

** Edit ** I managed to render them by using:

from django_crispy.bootstrap import InlineCheckboxes
self.helper.layout = Layout(InlineCheckboxes('my_field'))

Solution

  • from crispy_forms.bootstrap import InlineRadios
    
    class DhcpForm(forms.ModelForm):
            cargo = forms.ChoiceField(label='Cargo on Deck',
                              choices=[('true', 'Yes'),
                                       ('false', 'No')]
    def __init__(self, *args, **kwargs):
        self.helper.layout = Layout(
            InlineRadios('cargo', id="radio_id"))