Django - How To Display Model's Choices as Checkboxes

13,526

Solution 1

You need to use forms.RadioSelect() instead of forms.CheckboxSelectMultiple() since its single valued.

To override widgets for ModelForm, check the doc

class AddCar(forms.ModelForm):
    class Meta:
        model = Car
        widgets = {'type': forms.RadioSelect}

Or as in your question, the type line should be above the class Meta line, inside AddCar

class AddCar(forms.ModelForm):
    type = forms.ChoiceField(choices=Car.SCENERY_CHOICES, widget=forms.RadioSelect)

    class Meta:
        model = Car

Solution 2

You're using Route.SCENERY_CHOICES not Car.TYPE_CHOICES

Share:
13,526
howtodothis
Author by

howtodothis

Updated on June 05, 2022

Comments

  • howtodothis
    howtodothis over 1 year

    I followed this but I am still unable to display CHOICES as checkboxes on my form.

    models.py

    class Car(models.Model):
        TYPE_CHOICES = (
           ('s', 'small'),
           ('m', 'medium'),
           ('b', 'big'),
         )
         type = models.CharField(max_length=1, choices=TYPE_CHOICES)
    

    forms.py

    from django import forms
    from django.forms.widgets import CheckboxSelectMultiple
    
    from cars.models import Car
    
    class AddCar(forms.ModelForm):
        class Meta:
            model = Car
            type = forms.MultipleChoiceField(choices=Car.TYPE_CHOICES, widget=forms.CheckboxSelectMultiple())