问题 Django表格与一对多的关系


我在Django中有一个表单 PersonForm 这个表格模型有一个 一对多的关系 与汽车。当像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")

因此,在个人形式中,我需要显示汽车列表,该人员是允许选择/取消选择它们的所有者。我假设我可以在表格中这样做,即使用相关名称之类的东西。


12553
2018-01-10 14:20


起源



答案:


听起来像你想要的 内联模型表单。这使您能够在Person表单中的Person中添加/删除Car对象。

之前的链接是针对inlinemodeladmin的。下一个链接是内联表单: https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#modelforms-factory


11
2018-01-10 14:26



现在很酷,我知道它叫什么。谢谢 - Prometheus


答案:


听起来像你想要的 内联模型表单。这使您能够在Person表单中的Person中添加/删除Car对象。

之前的链接是针对inlinemodeladmin的。下一个链接是内联表单: https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#modelforms-factory


11
2018-01-10 14:26



现在很酷,我知道它叫什么。谢谢 - Prometheus


我没有任何机会使用内联formset,所以我建议覆盖你的模型的保存方法,我觉得它更干:

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

0
2018-03-27 09:07