Django Multiple Choice Issues

I have two different problems with multiple selections in models.

First, I'm trying to make multiple selections so that the user can select 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 ManyToMany relation with the definition of a model in another model: First (import into the model):

 from events.models import Category 

The second (field associated with the model):

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

I get this error on syncdb:

Error: one or more models does not validate: situ.situ: 'day' has m2m relationships with model day, either not installed, or annotation.
situ.situ: 'type' has a m2m relationship with a Category model that has either not been installed or is abstract.

+4
source share
3 answers

you can use:

 day = forms.ModelMultipleChoiceField(queryset=Day.objects.all()) 
+5
source

Unfortunately, the ManyToMany relationship only works for relationships with other models, not values ​​from a set of options. Django does not provide an inline model field type with multiple choices. However, I have used this snippet in the past when using a multi-select box: http://www.djangosnippets.org/snippets/1200/

This encodes several selected options into a comma-separated list stored in CharField, which works great if you don't need to make any kind of connection or something in the selection. If you need to do this, you will need to define a new Day model in which you can use ManyToManyField.

The second problem, I believe, is the result of the first - if you fix this problem, you will be fine.

+4
source

For the first part of your questions. You must use 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 give a list of Unicode objects.

For the second problem, you need to either include the application name in the abstract model declaration 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 application in the models.py file, you can leave its Category , but since it is in another application, you need to specify the name of the application.

+2
source

Source: https://habr.com/ru/post/1342203/


All Articles