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

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

问题描述

我正在建立一个支持票据跟踪应用程序,并有一些模型,我想从一个页面创建。门票通过ForeignKey属于客户。笔记也通过ForeignKey属于门票。我想选择一个客户(这是一个单独的项目)或创建一个新的客户,然后创建一个票,最后创建一个分配给新票证的票据。

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,但是我想隐藏一些字段并进行一些复杂的验证。我正在寻找的控制水平似乎要求formet或手工做一切,完成一个乏味,手工编码的模板页面,我想避免。

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.

我有一些可爱的功能吗?有人有一个很好的参考或使用formets的例子?我花了整整一周的时间为他们的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()

这里是自定义验证的文档。

Here are the docs for custom validation.

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

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