Reputation: 3481
I need to create a field which can have multiple choices selected instead of one. These choices are fixed. For example:
we use CharField with choices option if we want one choice to be selected from multiple ones.
SEX_CHOICES = (('M', 'Male'),
('F', 'Female')
)
class Model1(models.Model):
name = models.CharField(max_length=30)
sex = models.CharField(max_length=1, choices=SEX_CHOICES)
But I need similar setup for multiple choice. I don't want to use ManyToManyField as the choices will be fixed and not changing as time goes by.
Please guide.
Upvotes: 1
Views: 1806
Reputation: 76
You have three basic choices:
If they really don't change, I'd go with #2. Having a bunch of booleanfields is a good representation of a set of choices that don't change.
Upvotes: 2
Reputation: 4245
Check multiselect field package. It does what you want to and it works well (at least when I used it 4 months ago). You can also check https://pypi.python.org/pypi/django-select-multiple-field/ but I haven't tested it.
Upvotes: 1
Reputation: 6009
I think you searching for something like this
from django import forms
class Test(forms.Form):
OPTIONS = (
("a", "A"),
("b", "B"),
)
name = forms.MultipleChoiceField(widget=forms.SelectMultiple,choices=OPTIONS)
Upvotes: 0
Reputation: 5656
To just have multipleselect you can add widget = forms.SelectMultiple as widget for that field in form.
But bigger problem is saving the selected stuff. For that you would have to write your own field, which is able to save the multiple choices into single CharField.
Check out this page: https://docs.djangoproject.com/en/dev/howto/custom-model-fields/
Upvotes: 1