python - 具有一对多关系的 Django Form

标签 python django django-forms

我在 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/

相关文章:

django - 限制用户使用特定域注册: django

python - 如何将python屏幕输出保存到文本文件

python - Google App Engine 投影查询可以返回实体键吗?

python - Python 对象数据库列表

python - 安装 askbot 后 Django 应用程序未运行

python - Django基于添加表单编辑表单?

django - 如何查询人的内容(帖子/视频),当用户的详细信息和关注列表在单独的数据库中时,用户使用 Django ORM 关注

python - 我如何检测我的窗口何时被 wxPython 最小化?

python - Django 将 ManyToManyField 添加到 ModelForm

python - django 验证器和 clean_field 方法之间的区别