python - Django SelectMultiple fails to display saved choices -


i'm doing admin form selectmultiple dynamically populated choices in django 1.10

this model:

class helprequest(models.model):     name = models.charfield(max_length=32)     groups = models.textfield(blank=true) 

this form:

class adminhelprequestform(modelform):     def __init__(self, *args, **kwargs):          super().__init__(*args, **kwargs)          self.fields['groups'] = forms.multiplechoicefield(choices=groups_from_ldap,                                                      widget=selectmultiple(attrs={'class': 'chosen'}))      class meta:         model = helprequest         fields = ('name', 'groups') 

the form gets used in admin:

@admin.register(helprequest) class helprequestadmin(admin.modeladmin):     form = adminhelprequestform  

the selectmultiple saves choices fine model

>>> ar = helprequest.objects.get(pk=1) >>> print(ar.groups) ['mygroup', 'othergroup', 'yetanothergroup'] 

but not display saved choices model instance in widget.

what's wrong here?

somehow counter-intuitively solution add custom clean create comma separated string of choices , splitting string list , manually setting initial:

class adminhelprequestform(modelform):    def __init__(self, *args, **kwargs):       super().__init__(*args, **kwargs)       self.fields['groups'] = forms.multiplechoicefield(choices=groups_from_ldap,                                               widget=selectmultiple(attrs={'class': 'chosen'}))      if self.instance:         self.initial['groups'] = self.instance.groups.split(',')  class meta:     model = helprequest     fields = ('name', 'groups')  def clean_groups(self):     groups = self.cleaned_data['groups']     if groups:         assert isinstance(groups, (list, tuple))         return str(','.join(groups))     else:     return '' 

this has nice benefit of making groups rather concise , readable in admin list view.

another, more concise possibility not have clean function @ all, , go ast.literal_eval:

import ast  class adminhelprequestform(modelform):    def __init__(self, *args, **kwargs):       super().__init__(*args, **kwargs)       self.fields['groups'] = forms.multiplechoicefield(choices=groups_from_ldap,                                               widget=selectmultiple(attrs={'class': 'chosen'}))      if self.instance.groups:         self.initial['groups'] = ast.literal.eval(self.instance.groups)  class meta:     model = helprequest     fields = ('name', 'groups') 

Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -