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类。
__init__
Action_Form
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')
1.如何使ModelMultipleChoiceField接受那些“初始”值? 这可以在你的Action_Form __init__方法中使用ModelMultipleChoiceField initial属性来完成。
Action_Form __init__
就像在Django源代码(db / models / fields / related.py)中所说的def formfield(self, **kwargs):
def formfield(self, **kwargs)
# If initial is passed in, it's a list of related objects, but the # MultipleChoiceField takes a list of IDs.
因此,你需要为其提供ID列表:
class Action_Form(forms.ModelForm): def __init__(self, *args, **kwargs): super(Action_Form, self).__init__(*args, **kwargs) self.fields['from_company'].initial = [c.pk for c in Contact.object.filter()]