Note that there are some explanatory texts on larger screens.

plurals
  1. PODjango: ModelMultipleChoiceField doesn't select initial choices
    primarykey
    data
    text
    <p>ModelMultipleChoiceField doesn't select initial choices and I can't make the following fix (link below) work in my example:</p> <p><a href="http://code.djangoproject.com/ticket/5247#comment:6" rel="noreferrer">http://code.djangoproject.com/ticket/5247#comment:6</a></p> <p>My models and form:</p> <pre><code>class Company(models.Model): company_name = models.CharField(max_length=200) class Contact(models.Model): company = models.ForeignKey(Company) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) class Action(models.Model): company = models.ForeignKey(Company, blank=True, null=True) from_company = models.ManyToManyField(Contact, verbose_name='Participant(s) from "Company"', blank=True, null=True) class Action_Form(ModelForm): from_company = forms.ModelMultipleChoiceField(queryset=Contact.objects.none(), widget=forms.CheckboxSelectMultiple()) class Meta: model = Action </code></pre> <p>What I do and the results:</p> <pre> >>> contacts_from_company = Contact.objects.filter(company__exact=1) # "1" for test, otherwise a variable >>> form = Action_Form(initial={'from_company': [o.pk for o in contacts_from_company]}) # as suggested in the fix >>> print form['from_company'] &lt;ul&gt; &lt;/ul&gt; >>> print contacts_from_company [&lt;Contact: test person&gt;, &lt;Contact: another person&gt;] >>> form2 = Action_Form(initial={'from_company': contacts_from_company}) >>> print form2['from_company'] &lt;ul&gt; &lt;/ul&gt; >>> form3 = Action_Form(initial={'from_company': Contact.objects.all()}) >>> print form3['from_company'] &lt;ul&gt; &lt;/ul&gt; </pre> <p>The way I was hoping it would work:<br> 1. My view gets "company" from request.GET<br> 2. It then filters all "contacts" for that "company"<br> 3. Finally, it creates a form and passes those "contacts" as "initial={...}" </p> <p><strong>Two questions:</strong><br> <strong>1. [not answered yet]</strong> How can I make ModelMultipleChoiceField take those "initial" values?<br> <strong>2. [answered]</strong> As an alternative, can I pass a variable to Action_Form(ModelForm) so that in my ModelForm I could have:</p> <pre> from_company = forms.ModelMultipleChoiceField(queryset=Contact.objects.filter(company__exact=some_id) # where some_id comes from a view </pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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