Home > Software engineering >  How to render Django CheckoxInput in a grid from Modelform?
How to render Django CheckoxInput in a grid from Modelform?

Time:11-26

models.py

class MyModel(Model):
    author = ForeignKey(settings.AUTH_USER_MODEL, on_delete=CASCADE)
    title = CharField(max_length=200, default='')
    text = TextField(default='')
    choice_1 = BooleanField(default=False)
    choice_2 = BooleanField(default=False)
    choice_3 = BooleanField(default=False)
    choice_4 = BooleanField(default=False)
    choice_5 = BooleanField(default=False)
    choice_6 = BooleanField(default=False)

    def __str__(self):
        return self.title

forms.py

class MyModelForm(ModelForm):
        class Meta:
        model = MyModel
        fields = [
            'title',
            'text',
            'choice_1',
            'choice_2',
            'choice_3',
            'choice_4',
            'choice_5',
            'choice_6'
        ]

        widgets = {
            'text': Textarea(),
            'choice_1': CheckboxInput(),
            'choice_2': CheckboxInput(),
            'choice_3': CheckboxInput(),
            'choice_4': CheckboxInput(),
            'choice_5': CheckboxInput(),
            'choice_6': CheckboxInput()
        }

I am using the django bootstrap 5 integration and attempting to render the checkboxes on a grid like this:

{% extends "base.html" %}
{% block content %}
{% load static %}
{% load bootstrap5 %}
{% bootstrap_css %}
{% bootstrap_javascript %}
{% bootstrap_messages %}

(Other code here...)

<div class="row-cols-4">
            {% for field in form %}
                    <div class="col-sm">{% bootstrap_field field layout='horizontal'%}</div>
            {% endfor %}
        </div>

However, the row and column css (also from bootstrap 5) seem to do absolutely nothing, and it's not really clear to me why this is the case. What am I doing wrong here?

CodePudding user response:

You should include the row class too

<div class="row row-cols-4">
    {% for field in form %}
        <div class="col-sm">{% bootstrap_field field layout='horizontal'%}</div>
    {% endfor %}
</div>
  • Related