mardi 18 octobre 2022

Django crispy forms inline checkboxes

I am using Django-cripsy-forms to build a form. I have a model with several attributes (MultiSelectField) all with the same choices (CHOICES).

from django.db import models
class Visit(models.Model):
    CHOICES = (
        ("A","A"),
        ("B","B"),
        ("C","C"),
        ("D","D"),
    )

    q1 = MultiSelectField(null=True, choices=CHOICES, blank=True)
    q2 = MultiSelectField(null=True, choices=CHOICES, blank=True)
    q3 = MultiSelectField(null=True, choices=CHOICES, blank=True)
    q4 = MultiSelectField(null=True, choices=CHOICES, blank=True)
    q5 = MultiSelectField(null=True, choices=CHOICES, blank=True)
    q6 = MultiSelectField(null=True, choices=CHOICES, blank=True)

I want to make a form with checkboxes for each choice for all attributes. But to avoid clutter want to have the checkboxes in-line. Sort of like a questionnaire (example below)

enter image description here

I tried using django-crispy-forms InlineCheckboxes as shown below. But the checkboxes would never be displayed inline. But would be displayed as shown in the picture below. I also tried editing the styling of the labels and inputs of individual checkboxes but that also didn't work. What am I doing wrong? And is there a better way of doing this?

from django import forms
from django.forms import ModelForm
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout
from crispy_forms.bootstrap import InlineCheckboxes

class VisitForm(ModelForm):
    class Meta:
        model = Visit
        fields = '__all__'
        widgets = {
            'q1': forms.CheckboxSelectMultiple(),
            'q2': forms.CheckboxSelectMultiple(),
            'q3': forms.CheckboxSelectMultiple(),
            'q4': forms.CheckboxSelectMultiple(),
            'q5': forms.CheckboxSelectMultiple(),
            'q6': forms.CheckboxSelectMultiple(),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.layout = Layout (
            InlineCheckboxes("q1"),
            InlineCheckboxes("q2"),
            InlineCheckboxes("q3"),
            InlineCheckboxes("q4"),
            InlineCheckboxes("q5"),
            InlineCheckboxes("q6"),
        )

enter image description here

The html of this is the following

<div id="div_id_signal" class="control-group">
    <label for="id_signal" class="control-label">Q1</label>
<div class="controls">
    <label class="checkbox inline" for="id_signal_0">
        <input type="checkbox" name="signal" id="id_signal_0" value="A">
        A
        </label>
</div>
</div>



Aucun commentaire:

Enregistrer un commentaire