如何在 Modelform 的网格中呈现 Django CheckoxInput?

How to render Django CheckoxInput in a grid from Modelform?

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()
        }

我正在使用 django bootstrap 5 integration 并尝试在这样的网格上呈现复选框:

{% 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>

然而,css 行和列(也来自 bootstrap 5)似乎完全没有做任何事情,我不太清楚为什么会这样。我在这里做错了什么?

您应该将 class 行添加到

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