[英]Django Form with a one-to-many relationship
我在 Django 中有一个名为PersonForm
的表单,这个表单模型与 Car 有一对多的关系。 当像在 Django Admin 中一样显示 PersonForm 时,我想允许我的用户从汽车等列表中选择/取消选择。这可能吗? 我正在寻找有关从哪里开始的信息。
到目前为止,这是我对 PersonForm 所拥有的:
class PersonForm(forms.ModelForm):
class Meta:
model = Person
fields = ('description',)
模型:
class Person(models.Model):
description = models.CharField(max_length="150")
class Car(models.Model):
make = models.CharField(max_length="25")
owner = models.ForeignKey('Person', related_name="Car")
因此,在个人表单中,我需要显示该人是允许选择/取消选择它们的所有者的汽车列表。 我假设我可以在表单中执行此操作,即使用相关名称之类的内容。
听起来您想要一个内联模型表单。 这使您能够从 Person 表单中的 Person 添加/删除 Car 对象。
之前的链接是针对 inlinemodeladmin 的。 下一个链接用于内联表单: https : //docs.djangoproject.com/en/dev/topics/forms/modelforms/#modelforms-factory
我没有任何机会使用内联表单集,所以我建议覆盖模型的保存方法,我觉得它更 DRY:
class PersonForm(forms.ModelForm):
# add a field to select a car
car = forms.ModelChoiceField(car.objects.all())
class Meta:
model = Person
fields = ('description', 'car')
def save(self, commit=True):
instance = super().save(commit)
# set Car reverse foreign key from the Person model
instance.car_set.add(self.cleaned_data['car']))
return instance
我知道这是一个旧线程,但由于我发现自己在搜索时几乎完全由 google 指向这里,因此我想我会为其他寻找答案的人提供以下内容。
我认为答案是使用
https://docs.djangoproject.com/en/3.1/ref/forms/fields/#modelchoicefield
或者
https://docs.djangoproject.com/en/3.1/ref/forms/fields/#modelmultiplechoicefield
有一篇关于如何使用 modelmultiplechoicefield 的好文章:
https://medium.com/swlh/django-forms-for-many-to-many-fields-d977dec4b024
但它也适用于一对多领域。 这些允许我们根据模型中的相关字段生成具有多个选项的表单作为复选框或类似的小部件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.