django multiple choice model problems

6.8k Views Asked by At

I have two diferents problems with multple choices in models.

The first, i'm trying to do a multiple choice so the user can pick one or more days of the week:

DAYS_CHOICES = (
    (1, _('Monday')),
    ...
    (7, _('Sunday')),
)
...
day = models.ManyToManyField('day', choices=DAYS_CHOICES)

The second problem:

I want to make a ManyToMany Relation with a model define in other model: First (Import to the model):

from events.models import Category

Second (The field related to the model):

type = models.ManyToManyField('Category', null=True, blank=True)

I get this error on syncdb:

Error: One or more models did not validate: situ.situ: 'day' has an m2m relation with model day, which has either not been installed or is abstract.
situ.situ: 'type' has an m2m relation with model Category, which has either not been installed or is abstract.

3

There are 3 best solutions below

2
On

For the first part of your questions. You should be using a MultipleChoiceField

DAYS_CHOICES = (
    (1, _('Monday')),
    ...
    (7, _('Sunday')),
)
...
days = forms.MultipleChoiceField(choices=DAYS_CHOICES)

http://docs.djangoproject.com/en/dev/ref/forms/fields/#multiplechoicefield

This will yield a list of Unicode objects.

For the second problem, You need to either include the app name in the abstract declaration of the model in the m2m field or not declare it abstractly.

type = models.ManyToManyField(Category, null=True, blank=True)

or

type = models.ManyToManyField('events.Category', null=True, blank=True)

If the Category model was defined later in the same app in the models.py you could leave it Category but since it is in another app, you need to specify the app name.

0
On

Unfortunately, the ManyToMany relation only works for relations with other models, not values from a choices set. Django does not provide a built in multiple choice model field type. However, I have used this snippet in the past when using a multiple select choices field: http://www.djangosnippets.org/snippets/1200/

This encodes the multiple selected options into a comma-separated list stored in a CharField, which works great, unless you need to do some sort of join or something on the selections. If you need to do that, you will have to define a new Day model that you can use the ManyToManyField on.

The second problem, I believe, is just the result of the first--if you clear up that issue, you'll be ok.

0
On

you could use :

day = forms.ModelMultipleChoiceField(queryset=Day.objects.all())