Django 2 模型 1 形式 [英] Django 2 models 1 form

查看:20
本文介绍了Django 2 模型 1 形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我仍然是 Django 的菜鸟,我想知道如何执行以下操作:

So, I'm still a total noob at Django and I was wondering how to do the following:

所以可以说我有类似下面的代码:

So lets say that I have something like the below code:

class UserProfile(models.Model):
    #Some fields
class UserProfileOther(models.Model):
    #Some other fields that I want in another table for organization
    user_profile = models.OneToOneField(UserProfile)

我现在如何创建包含上述两种模型的表单?

How do I now create a form that includes both of the above models?

推荐答案

您可以创建两个单独的 ModelForm 类.但在您看来,您必须为其实例添加前缀.

You can create two separate ModelForm classes. But in your view, you have to add a prefix to their instances.

def viewname(request):
    if request.method == 'POST':
        form1 = forms.YourForm(request.POST, prefix="form1")
        form2 = forms.YourOtherForm(request.POST, prefix="form2")
        if form1.is_valid() and form2.is_valid():
            # process valid forms
    else:
        form1 = forms.YourForm(prefix="form1")
        form2 = forms.YourOtherForm(prefix="form2")

    ....

使用前缀可确保不会混淆具有相似名称的字段.

Using a prefix ensures that fields with similar names are not mixed up.

这篇关于Django 2 模型 1 形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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