单个django ModelForm中的多个模型? [英] Multiple Models in a single django ModelForm?

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

问题描述

是否可以在django中的单个 ModelForm 中包含多个模型?我正在尝试创建个人资料编辑表单。所以我需要在UserProfile模型的用户模型中添加一些字段。目前我正在使用这样的两种形式

Is it possible to have multiple models included in a single ModelForm in django? I am trying to create a profile edit form. So I need to include some fields from the User model and the UserProfile model. Currently I am using 2 forms like this

class UserEditForm(ModelForm):

    class Meta:
        model = User
        fields = ("first_name", "last_name")

class UserProfileForm(ModelForm):

    class Meta:
        model = UserProfile
        fields = ("middle_name", "home_phone", "work_phone", "cell_phone")

有没有办法将这些整合成一种形式,或者我只需要创建一个表单并处理db加载并保存自己?

Is there a way to consolidate these into one form or do I just need to create a form and handle the db loading and saving myself?

推荐答案

您可以在一个< form> html元素内的模板中显示两个表单。然后在视图中单独处理表单。您仍然可以使用 form.save(),而不必处理数据库加载并保存自己。

You can just show both forms in the template inside of one <form> html element. Then just process the forms separately in the view. You'll still be able to use form.save() and not have to process db loading and saving yourself.

在这种情况下,您不应该需要它,但是如果要使用具有相同字段名称的表单,请查看django表单的前缀 kwarg。 (我回答了一个关于它的问题 here )。

In this case you shouldn't need it, but if you're going to be using forms with the same field names, look into the prefix kwarg for django forms. (I answered a question about it here).

这篇关于单个django ModelForm中的多个模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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