使用内联表单集创建模型和相关模型 [英] Creating a model and related models with Inline formsets
问题描述
[我已将其发布到 Django 用户 |Google 网上论坛也是.]
[I have posted this at the Django users | Google Groups also.]
使用内联表单集文档,我能够编辑属于特定模型的对象(使用模型).我一直在尝试遵循相同的模式创建 使用内联表单集的新对象,但一直无法我的头脑清醒到足以为此目的提出工作观点.
Using the example in the inline formset docs, I am able to edit objects belonging a particular model (using modelforms). I have been trying to follow the same pattern for creating new objects using inline formsets, but have been unable to clear my head enough to bring out a working view for this purpose.
使用与上述链接相同的示例,我将如何进行创建一个作者"模型的新实例及其相关的书"对象?
Using the same example as in the above link, how would I go about creating a new instance of an "Author" model together with its related "Book" objects?
推荐答案
首先,创建一个 Author 模型表单.
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
<小时>
要在新表单上没有复选框,请使用模板:
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 %}
这篇关于使用内联表单集创建模型和相关模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!