我在 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")
因此,在人员表单中,我需要显示该人员是车主的汽车列表,并允许选择/取消选择这些汽车。我假设我可以在表单中执行此操作,即使用相关名称之类的东西。
最佳答案
听起来像你想要的an inline model form .这使您能够在 Person 表单中的 Person 中添加/删除 Car 对象。
之前的链接是针对 inlinemodeladmin 的。下一个链接用于内联表单: https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#modelforms-factory
关于python - 具有一对多关系的 Django Form,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21046626/