Django:使用表单在一个模板中的多个模型 [英] Django: multiple models in one template using forms

查看:37
本文介绍了Django:使用表单在一个模板中的多个模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个支持工单跟踪应用程序,我想从一个页面创建几个模型.票通过外键属于客户.笔记也通过外键属于票证.我想要选择一个客户(这是一个完整的独立项目)或创建一个新客户,然后创建一个票证,最后创建一个分配给新票证的注释.

I'm building a support ticket tracking app and have a few models I'd like to create from one page. Tickets belong to a Customer via a ForeignKey. Notes belong to Tickets via a ForeignKey as well. I'd like to have the option of selecting a Customer (that's a whole separate project) OR creating a new Customer, then creating a Ticket and finally creating a Note assigned to the new ticket.

由于我对 Django 比较陌生,所以我倾向于反复工作,每次都尝试新功能.我玩过 ModelForms,但我想隐藏一些字段并进行一些复杂的验证.似乎我正在寻找的控制级别要么需要表单集,要么手动完成所有工作,并带有我试图避免的乏味的手工编码模板页面.

Since I'm fairly new to Django, I tend to work iteratively, trying out new features each time. I've played with ModelForms but I want to hide some of the fields and do some complex validation. It seems like the level of control I'm looking for either requires formsets or doing everything by hand, complete with a tedious, hand-coded template page, which I'm trying to avoid.

有什么我遗漏的可爱功能吗?有人有使用表单集的良好参考或示例吗?我在他们的 API 文档上花了整个周末,但我仍然一无所知.如果我分解并手工编写所有内容,这是设计问题吗?

Is there some lovely feature I'm missing? Does someone have a good reference or example for using formsets? I spent a whole weekend on the API docs for them and I'm still clueless. Is it a design issue if I break down and hand-code everything?

推荐答案

使用 ModelForms.假设您有表单 A、B 和 C.您打印出每个表单和页面,现在您需要处理 POST.

This really isn't too hard to implement with ModelForms. So lets say you have Forms A, B, and C. You print out each of the forms and the page and now you need to handle the POST.

if request.POST():
    a_valid = formA.is_valid()
    b_valid = formB.is_valid()
    c_valid = formC.is_valid()
    # we do this since 'and' short circuits and we want to check to whole page for form errors
    if a_valid and b_valid and c_valid:
        a = formA.save()
        b = formB.save(commit=False)
        c = formC.save(commit=False)
        b.foreignkeytoA = a
        b.save()
        c.foreignkeytoB = b
        c.save()

这里是自定义验证.

这篇关于Django:使用表单在一个模板中的多个模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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