Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in django admin, can we have a multiple select based on choices

http://docs.djangoproject.com/en/dev/ref/models/fields/#choices

i've read through the documentation and this implies using a database table for dynamic data, however it states

choices is meant for static data that doesn't change much, if ever.

so what if i want to use choices, but have it select multiple because the data i'm using is quite static, e.g days of the week.

is there anyway to achieve this without a database table?

like image 313
Rasiel Avatar asked Nov 10 '09 21:11

Rasiel


2 Answers

ChoiceField is not really suitable for multiple choices, instead I would use a ManyToManyField. Ignore the fact that Choices can be used instead of ForeignKey for static data for now. If it turns out to be a performance issue, there are ways to represent this differently (one being a binary mask approach), but they require way more work.

like image 81
John Paulett Avatar answered Sep 28 '22 17:09

John Paulett


This worked for me:

1) create a Form class and set an attribute to provide your static choices to a MultipleChoiceField

from django import forms
from myapp.models import MyModel, MYCHOICES

class MyForm(forms.ModelForm):
    myfield = forms.MultipleChoiceField(choices=MYCHOICES, widget=forms.SelectMultiple)
    class Meta:
        model = MyModel

2) then, if you're using the admin interface, set the form attribute in your admin class so tit will use your customized form

from myapp.models import MyModel
from myapp.forms import MyForm
from django.contrib import admin

class MyAdmin(admin.ModelAdmin):
    form = MyForm

admin.site.register(MyModel, MyAdmin)
like image 40
Adrian Avatar answered Sep 28 '22 17:09

Adrian