I know there isn't MultipleChoiceField
for a Model, you can only use it on Forms.
Today I face an issue when analyzing a new project related with Multiple Choices.
I would like to have a field like a CharField
with choices
with the option of multiple choice.
I solved this issue other times by creating a CharField
and managed the multiple choices in the form with a forms.MultipleChoiceField
and store the choices separated by commas.
In this project, due to configuration, I cannot do it as I mention above, I need to do it in the Models, and I prefer NOT to edit the Django admin form neither use forms. I need a Model Field with multiple choices option
Maybe overriding some of the models function or using a custom widget... I don't know, I'm kinda lost here.
I'm aware off simple choices, I would like to have something like:
class MODEL(models.Model): MY_CHOICES = ( ('a', 'Hola'), ('b', 'Hello'), ('c', 'Bonjour'), ('d', 'Boas'), ) ... ... my_field = models.CharField(max_length=1, choices=MY_CHOICES) ...
but with the capability of saving multiple choices not only 1 choice.
To add a multiple choice field with Python Django, we can add a ManyToManyField . to create the choices field in the Profile model which is a ManyToManyField . We use Choices as the argument to allow Choices values as the values for choices .
A ManyToMany field is used when a model needs to reference multiple instances of another model. Use cases include: A user needs to assign multiple categories to a blog post. A user wants to add multiple blog posts to a publication.
A widget is Django's representation of an HTML input element. The widget handles the rendering of the HTML, and the extraction of data from a GET/POST dictionary that corresponds to the widget. The HTML generated by the built-in widgets uses HTML5 syntax, targeting <! DOCTYPE html> .
You need to think about how you are going to store the data at a database level. This will dictate your solution.
Presumably, you want a single column in a table that is storing multiple values. This will also force you to think about how you will serialize - for example, you can't simply do comma separated if you need to store strings that might contain commas.
However, you are probably best off using a solution like django-multiselectfield
In case You are using Postgres consider using ArrayField.
from django.db import models from django.contrib.postgres.fields import ArrayField class WhateverModel(models.Model): WHATEVER_CHOICE = u'1' SAMPLE_CHOICES = ( (WHATEVER_CHOICE, u'one'), ) choices = ArrayField( models.CharField(choices=SAMPLE_CHOICES, max_length=2, blank=True, default=WHATEVER_CHOICE), )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With