简体   繁体   English

在Django中将外键子项添加到模型表单中

[英]Add foreign key children to model form in Django

I have the following Django models: 我有以下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')

So any contact object can have up to four contact types, with each type either being present or absent. 因此,任何联系对象最多可以有四种联系类型,每种类型都存在或不存在。 I would like to make a Model Form for Contact with a multiple choice field for contact type. 我想为Contact制作一个模型表格,其中包含联系人类型的多选字段。 How can I populate this contact type field with the existing values when I construct the Contact form with a Contact instance? 当我使用Contact实例构建Contact表单时,如何使用现有值填充此联系类型字段?

Edit: To clarify, I want one checkbox to be created for each of those four choices, and if the form is instantiated with a model instance, then I want the checkboxes to be checked for each of the related objects that exists, similar to what happens automatically with the rest of the fields. 编辑:为了澄清,我希望为这四个选项中的每一个创建一个复选框,如果表单是使用模型实例实例化的,那么我希望检查每个存在的相关对象的复选框,类似于与其他字段自动发生。

I would probably structure the models as such, so I can choose which contact type when creating/editing the Contact. 我可能会这样构建模型,因此我可以在创建/编辑联系人时选择哪种联系人类型。 If ContactType is related as a ManyToMany, we automatically get a ModelMultpleChoiceField in the ModelForm, and all we need to do is use the CheckboxSelectMultiple widget to get the output you're looking for. 如果ContactType与ManyToMany相关,我们会自动在ModelForm中获取ModelMultpleChoiceField,我们需要做的就是使用CheckboxSelectMultiple小部件来获取您正在寻找的输出。

When we pass an instance of Contact to the ContactForm, Django will bind any pre-selected ContactType choices and check the checkboxes for us. 当我们将Contact的一个实例传递给ContactForm时,Django将绑定任何预先选择的ContactType选项并检查我们的复选框。

Setting the title of each ContactType to unique does the same as unique_together on the contact and contact_type. 将每个ContactType的标题设置为唯一与联系人和contact_type上的unique_together相同。

#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()

Have you tried something like this? 你尝试过这样的事吗?

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})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM