在Django模型表单中添加外键子项
我有以下的Django模型:
class Contact(models.Model):
id #primary key
#Other contact info
class ContactType(models.Model):
contacttype_choices=(('Primary', 'Primary'),
('Billing', 'Billing'),
('Business', 'Business'),
('Technology', 'Technology'))
contact=models.ForeignKey(Contact)
type=models.CharField(choices=contacttype_choices, max_length=30)
class Meta:
unique_together=('contact', 'type')
所以任何一个联系对象可以有最多四种联系类型,每种类型可以有或者没有。我想为Contact
创建一个模型表单,这个表单里有一个多选框,用来选择联系类型。请问我该如何在构建Contact表单时,把已有的联系类型填充到这个多选框里呢?
补充说明:为了更清楚,我希望为这四个选择中的每一个创建一个复选框。如果这个表单是用一个模型实例来生成的,那么我希望复选框能根据已有的相关对象自动勾选,就像其他字段那样。
2 个回答
1
你试过像这样做吗?
class ContactForm(forms.ModelForm):
class Meta:
model = Contact
def __init__(self, *args, **kwargs):
super(ContactForm, self).__init__(*args, **kwargs)
self.fields['contacttypes'] = forms.MultipleChoiceField(
choices = CONTACT_TYPE_CHOICES,
label = "contact type",
widget = CheckBoxSelectMultiple
)
contact = Contact.objects.get(pk=1) # or whatever
types = ContactType.objects.filter(contact = contact)
form = ContactForm(instance=contact, initial={'contacttypes' : types})
1
我可能会这样设计模型,这样在创建或编辑联系人的时候,就可以选择联系人类型。如果联系人类型是多对多的关系,我们在模型表单中就会自动得到一个可以选择多个选项的字段。我们只需要使用CheckboxSelectMultiple这个工具,就能得到你想要的效果。
当我们把一个联系人实例传给联系人表单时,Django会自动把之前选好的联系人类型绑定上,并帮我们勾选好复选框。
把每个联系人类型的标题设置为唯一,就和在联系人和联系人类型上设置唯一组合是一样的效果。
#models.py
class Contact(models.Model):
#other fields
contact_types = models.ManyToMany(ContactType)
class ContactType(models.Model):
title = models.CharField(max_length=20, unique=true)
#forms.py
class ContactForm(forms.ModelForm):
class Meta:
model = Contact
def __init__(self, *args, **kwargs):
super(ContactForm, self).__init__(*args, **kwargs)
self.fields['contact_types'].widget = forms.CheckboxSelectMultiple()