I have a Django application and want to display multiple choice checkboxes in an Django's admin interface. I do not want to create a separate model for my choices by using a ManyToManyField.
models.py
from django.db import models
STAFF_BUSINESS_TYPES = {
(1, "Foo"),
(2, "Bar"),
(3, "Cat"),
(4, "Dog")
}
class Business(models.Model):
name = models.CharField(max_length=255, unique=True)
business_types = models.CommaSeparatedIntegerField(max_length=32, choices=STAFF_BUSINESS_TYPES)
forms.py
from business.models import Business, STAFF_BUSINESS_TYPES
from django.forms import CheckboxSelectMultiple, ModelForm, MultipleChoiceField
class BusinessForm(ModelForm):
business_types = MultipleChoiceField(required=True, widget=CheckboxSelectMultiple, choices=STAFF_BUSINESS_TYPES)
class Meta:
model = Business
fields = ['name', 'business_types']
def clean_business_types(self):
data = self.cleaned_data['business_types']
cleaned_data = ",".join(data)
return cleaned_data
admin.py
from django.contrib import admin
from business.models import Business
from business.forms import BusinessForm
@admin.register(Business)
class BusinessAdmin(admin.ModelAdmin):
form = BusinessForm
However, when I attempt to add a business with type "Bar":
Select a valid choice. 1 is not one of the available choices.
Likewise with when I attempt to add a business with multiple values selected:
Select a valid choice. 1,2 is not one of the available choices.
How is 1 not a valid choice, considering (1, "Foo") is within my choices? Is it invalid to use Django's built in Comma Separated Integer field like this?