在 Django 视图中结合 modelformset 和 inlineformset [英] combine modelformset and inlineformset in django views

查看:18
本文介绍了在 Django 视图中结合 modelformset 和 inlineformset的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型

   class A(models.Model):
        name = models.CharField(50)
        type = models.CharField(50)

   class B(models.Model):
        field1 = ForeignKeyField(A)
        value = IntegerField()

我想通过 ModelFormSet(来自模型 A)显示多个表单,其中每个表单依次显示连接到该对象的所有对象的 InlineFormSets(来自模型 B).

I'd like to display a number of forms via a ModelFormSet (from model A) where each one of the forms displays in turn InlineFormSets (from model B) for all objects connected to the object.

如何在 django 视图中将模型表单集(模型 A)和内联表单集(mdoel B)结合使用保存方法?

How can i combine both modelformsets (model A) and inline formsets (mdoel B) on save method in django views?

推荐答案

我不确定这是一个好的解决方案,但这是我能想出的唯一可行的解​​决方案.

I'm not sure this is a good solution, but it's the only solution I can come up with that will work.

我会创建一个字典列表.每个 Dictionary 都有一个 baseForm 键,用于保存您的 B 类表单和一个 inline_forms 键,用于保存您的 A 类 inline_formset.

I would create a List of Dictionaries. Each Dictionary will have a baseForm key which will hold your B class form and a inline_forms key which will hold your class A inline_formset.

在您的视图中,代码遍历列表并相应地打印表单.为每个表单提交按钮生成不同的值.例如第一个表单的 submit_1 , etch ..

In your view code iterate over the list and print the forms accordingly. Generate a different value for each of the forms submit button. For example submit_1 for the first form , etch ..

提交表单时,检查此值(提交按钮的值),如果该值为例如 submit_2,则您确定列表中的第二个项目/表单已提交.您可以从他们那里开始处理提交的数据.

When a form is submitted, check this value (the value of the submit button), if the value is for example submit_2 you are certain the second item/form of your list has been submitted. From their you can start processing the submitted data.

这篇关于在 Django 视图中结合 modelformset 和 inlineformset的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆