如何在Django中的表单中嵌套嵌入式表单集? [英] How to have a nested inline formset within a form in Django?

查看:288
本文介绍了如何在Django中的表单中嵌套嵌入式表单集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望这个问题还没有被问到,但是我想知道是否有可能为对象设置一个普通的基于类的表单,并在其中设置一个内联格式来编辑它的相关对象。

I hope this question has not been asked yet, but I want to know if it is possible to have a normal class-based form for an object and to have an inline formset inside it to edit its related objects.

例如,我有一个联系人模型


class Contact(models.Model):

...



和通信模型


class Communication(models.Model):

contact = models.ForeignKey(Contact)

For example, I have a Contact model
class Contact(models.Model):
...

And a Communication model
class Communication(models.Model):
contact = models.ForeignKey(Contact)

并且我想要一个嵌套在其中的联机表单来管理与之相关的通信。

and I want to have a form for Contact with a inline formset nested in it for managing communications related to it.

可以使用现有组件或者我有一个绝望的梦想?

Is it possible to do so with existing components or do I have a hopeless dream?

编辑:我知道管理面板是这样做的,但是如何在视图中进行工作?

EDIT : I know that the admin panel does it, but how do I make work in a view?

推荐答案

当然可以 - 你觉得管理员怎么看?

Of course it's possible - how do you think the admin does it?

查看内联表单文档

评论后编辑当然,您需要实例化和呈现两者父表单和嵌套表单集。如下所示:

Edited after comment Of course, you need to instantiate and render both the parent form and the nested formset. Something like:

def edit_contact(request, contact_pk=None):
    if contact_pk:
        my_contact = Contact.objects.get(pk=contact_pk)
    else:
        my_contact = Contact()
    CommunicationFormSet = inlineformset_factory(Contact, Communication)
    if request.POST:
        contact_form = ContactForm(request.POST, instance=my_contact)
        communication_set = CommunicationFormSet(request.POST,
                                                 instance=my_contact)
        if contact_form.is_valid() and communication_set.is_valid():
            contact_form.save()
            communication_set.save()
    else:
        contact_form = ContactForm(instance=my_contact)
        communication_set = CommunicationFormSet(instance=my_contact)

    return render_to_response('my_template.html', 
                              {'form': contact_form, 'formset':communication_set})

,模板可以简单到:

<form action="" method="POST">
  {{ form.as_p }}
  {{ formset }}
</form>

尽管您可能想要更详细地介绍如何呈现。

although you'll probably want to be a bit more detailed in how you render it.

这篇关于如何在Django中的表单中嵌套嵌入式表单集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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