gpt4 book ai didi

python - Django:ModelMultipleChoiceField 不选择初始选择

转载 作者:IT老高 更新时间:2023-10-28 22:20:36 25 4
gpt4 key购买 nike

ModelMultipleChoiceField 不选择初始选择,我无法在我的示例中进行以下修复(下面的链接):

http://code.djangoproject.com/ticket/5247#comment:6

我的模型和形式:

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.我的 View 从request.GET中得到“公司”
2. 然后过滤该“公司”的所有“联系人”
3. 最后,它创建一个表单并将那些“联系人”传递为“initial={...}”

两个问题:
<强> 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

最佳答案

我正在回复 1)

1. How can I make ModelMultipleChoiceField take those "initial" values?

这可以在您的 Action_Form __init__ 方法中使用 ModelMultipleChoiceField initial 属性来完成。

正如 Django 源代码中所说的 (db/models/fields/related.py)在 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()]

关于python - Django:ModelMultipleChoiceField 不选择初始选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/488036/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com