Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Django ModelField that allows for multiple choices, aside from ManyToMany?

I'd like the user to be able to make multiple selections via the admin interface, and store the result as a list of comma-separated values. A select-multiple or a list of checkboxes would be great. However, I don't need the items in this list of values to refer to any models in particular... I just want a text list of items, plain and simple, hence I don't think the ManyToManyField is the one I'm looking for. What's the quickest way to do this in Django?

like image 967
int3 Avatar asked Feb 15 '10 16:02

int3


People also ask

How can I have multiple models in a single Django ModelForm?

In a nutshell: Make a form for each model, submit them both to template in a single <form> , using prefix keyarg and have the view handle validation. If there is dependency, just make sure you save the "parent" model before dependant, and use parent's ID for foreign key before commiting save of "child" model.

What are the field types in Django models?

Fields in Django are the data types to store a particular type of data. For example, to store an integer, IntegerField would be used. These fields have in-built validation for a particular data type, that is you can not store “abc” in an IntegerField. Similarly, for other fields.

Is there an array field Django?

Notice how the ManyToManyField is now replaced by the ArrayField . To display the Array field in Django Admin, a Form for the field must be present. Since the array is made up of abstract Author models, the form can be easily created by using a ModelForm .

Can Django model have two primary keys?

Do Django models support multiple-column primary keys? ¶ No. Only single-column primary keys are supported.


2 Answers

There is a django snippet which does just this: multiple choice model field. It says:

Usually you want to store multiple choices as a manytomany link to another table. Sometimes however it is useful to store them in the model itself. This field implements a model field and an accompanying formfield to store multiple choices as a comma-separated list of values, using the normal CHOICES attribute.

like image 173
Alexander Torstling Avatar answered Sep 28 '22 09:09

Alexander Torstling


Django-multiselectfield does what you require:

https://github.com/goinnn/django-multiselectfield

It's inspired by the snippet that Alexander mentioned.

like image 45
Mick T Avatar answered Sep 28 '22 08:09

Mick T