Note that there are some explanatory texts on larger screens.

plurals
  1. PODjango: MultipleChoiceField in admin to carry over previously saved values
    text
    copied!<p>I am having troubles to carry over previously selected items in a ModelForm in the admin. I want to use the <em>forms.CheckboxSelectMultiple</em> widget since that is the most straightforward UI in this usecase. It works as far that when saving, the values are stored. But when editing the previously saved item, the values previously saved in this field are not reflected in the widget.</p> <p>UI Example:</p> <p><img src="https://i.stack.imgur.com/eL79A.png" alt="alt text"></p> <p>After posting (editing that item, returns it blank):</p> <p><img src="https://i.stack.imgur.com/bl9Bd.png" alt="alt text"></p> <p>However, when not using the widget but a regular CharField when editing the item it looks like:</p> <p><img src="https://i.stack.imgur.com/6dN1l.png" alt="alt text"></p> <p>So for some reason the values are not represented by the checkbox widget?</p> <p>Here's my simplified setup, models.py</p> <pre><code>POST_TYPES = ( ('blog', 'Blog'), ('portfolio', 'Portfolio'), ('beeldbank', 'Beeldbank'), ) class Module(models.Model): title = models.CharField(max_length=100, verbose_name='title') entriesFrom = models.CharField(max_length=100) def __unicode__(self): return self.title </code></pre> <p>forms.py:</p> <pre><code>class ModuleForm(forms.ModelForm): entriesFrom = forms.MultipleChoiceField( choices=POST_TYPES, widget=CheckboxSelectMultiple, label="Pull content from", required=False, show_hidden_initial=True) class Meta: model = Module def __init__(self, *args, **kwargs): super(ModuleForm, self).__init__(*args, **kwargs) if kwargs.has_key('instance'): instance = kwargs['instance'] self.fields['entriesFrom'].initial = instance.entriesFrom logging.debug(instance.entriesFrom) </code></pre> <p>admin.py</p> <pre><code>class ModuleAdmin(admin.ModelAdmin): form = ModuleForm </code></pre> <p>So when editing a previously saved item with say 'blog' selected, debugging on <strong>init</strong> returns me the correct values on self.fields['entriesFrom'] ([u'blog',]), but its not reflected in the checkboxes (nothing is shown as selected) in the admin.</p> <p><em>edit</em></p> <p>updated the ModuleForm class to pass on initial values, but nothing still gets pre-populated whilst there are a few values in the initial value ("[u'blog']").</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload