Django:ModelMultipleChoiceField不选择初始选择

ModelMultipleChoiceField没有选择初始选择,并且在我的示例中,我无法进行以下修复

我的模型和表格:

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

我的工作和结果:

>>> 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']

<ul>

</ul>

>>> print contacts_from_company

[<Contact: test person>, <Contact: another person>]

>>> form2 = Action_Form(initial={'from_company': contacts_from_company})

>>> print form2['from_company']

<ul>

</ul>

>>> form3 = Action_Form(initial={'from_company': Contact.objects.all()})

>>> print form3['from_company']

<ul>

</ul>

我希望它可以工作的方式:

1.我的视图从request.GET获取“公司”

2.然后过滤该“公司”的所有“联系人”

3.最后,它创建一个表单并将这些“联系人”作为“初始= {…}”

两个问题:

1. [尚未回答]如何使ModelMultipleChoiceField接受那些“初始”值?

2. [已回答]作为替代,我可以将变量传递给Action_Form(ModelForm)以便在我的ModelForm中可以有:

from_company = forms.ModelMultipleChoiceField(queryset=Contact.objects.filter(company__exact=some_id) # where some_id comes from a view

回答:

你将需要添加一个__init__方法来Action_Form设置初始值,记住要通过super调用__init__ModelForm类。

class Action_Form(forms.ModelForm):

def __init__(self, *args, **kwargs):

super(Action_Form, self).__init__(*args, **kwargs)

self.fields['from_company'].queryset = Contact.object.filter(...

如果你打算将过滤器参数作为关键字args传递给Action_Form,则需要在调用super之前将其删除:

myfilter = kwargs['myfilter']

del kwargs['myfilter']

或者,可能更好:

myfilter = kwargs.pop('myfilter')

以上是 Django:ModelMultipleChoiceField不选择初始选择 的全部内容, 来源链接: utcz.com/qa/428207.html

回到顶部