使用内联表单创建模型和相关模型

使用内联表单创建模型和相关模型

本文介绍了使用内联表单创建模型和相关模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[我已经发布在。]

[I have posted this at the Django users | Google Groups also.]

使用,我可以 编辑 属于某个模型的对象(使用
modelforms)。我一直在试图用
创建 新的对象,使用内联表单,但是一直无法使b $ b清除我的头足以带来出于此目的的工作视图。

Using the example in the inline formset docs, I am able to edit objects belonging a particular model (usingmodelforms). I have been trying to follow the same pattern forcreating new objects using inline formsets, but have been unable toclear my head enough to bring out a working view for this purpose.

使用与上述链接相同的示例,我将如何处理
创建作者的新实例模型及其相关的
Book对象?

Using the same example as in the above link, how would I go aboutcreating a new instance of an "Author" model together with its related"Book" objects?

推荐答案

首先,创建一个作者模型表单。 p>

First, create a Author model form.

author_form = AuthorModelForm()

然后创建一个虚拟作者对象:

then create a dummy author object:

author = Author()

然后使用虚拟作者创建一个内联表单,如下所示:

Then create a inline formset using the dummy author like so:

formset = BookFormSet(instance=author)  #since author is empty, this formset will just be empty forms

发送给模板。数据返回到视图后,您将创建作者:

Send that off to a template. After the data is returned back to the view, you create the Author:

author = AuthorModelForm(request.POST)
created_author = author.save()  # in practice make sure it's valid first

现在钩住内联表单与新创建的作者,然后保存:

Now hook the inline formset in with the newly created author and then save:

formset = BookFormSet(request.POST, instance=created_author)
formset.save()   #again, make sure it's valid first






编辑:


edit:

要在新表单上没有复选框,请执行以下操作:

To have no checkboxes on new forms, do this is a template:

{% for form in formset.forms %}
    <table>
    {% for field in form %}
        <tr><th>{{field.label_tag}}</th><td>{{field}}{{field.errors}}</td></tr>
    {% endfor %}

    {% if form.pk %} {# empty forms do not have a pk #}
         <tr><th>Delete?</th><td>{{field.DELETE}}</td></tr>
    {% endif %}
    </table>
{% endfor %}

这篇关于使用内联表单创建模型和相关模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 05:31