in django admin, can we have a multiple select bas

2019-04-10 13:23发布

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?

3条回答
We Are One
2楼-- · 2019-04-10 14:16

Try following configuration. In models.py

class MyModel(models.Model):
    my_choices = models.TextField(help_text="It's a good manners to write it")

in forms.py

CHOICES = ((1,1), (2,2))
class MyForm(forms.ModelForm):
    my_choices = forms.MultipleChoiceField(choices=CHOICES)

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        # maybe you can set initial with self.fields['my_choices'].initial = initial 
        # but it doesn't work wity dynamic choices
        obj = kwargs.get('instance')
        if obj:
            initial = [i for i in obj.my_choices.split(',')]
            self.initial['my_choices'] = initial

    def clean_lead_fields(self):
        return ','.join(self.cleaned_data.get('my_choices', []))

in admin.py

@admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):
    form = MyModelForm
查看更多
该账号已被封号
3楼-- · 2019-04-10 14:17

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)
查看更多
冷血范
4楼-- · 2019-04-10 14:25

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.

查看更多
登录 后发表回答