【问题标题】:multiple forms in Django createView classDjango createView 类中的多个表单
【发布时间】:2018-03-26 17:09:56
【问题描述】:

我想创建一个 formView(基于 Django 内置 CreateView 类)来允许创建来自两个不同模型的新用户记录。

两个模型听起来一个是用户模型,另一个是用户配置文件模式l。

我希望使用一个带有一个提交按钮的表单来处理它,但我发现在 Django 的一个 createView 类中只能分配一个 form_class

所以我想知道是否可以使用 CreateView 来接近它?如果没有,有什么解决方案推荐吗?如果您有任何帮助,我们将不胜感激。

【问题讨论】:

    标签: django django-views


    【解决方案1】:

    其实我找到了解决方案:使用 User 模型并以与下面相同的形式添加配置文件的字段

    类 userCreateForm:

        email = forms.EmailField(label=_("E-mail"))
        contact_number = forms.CharField(label=_("Contact"))
        contact_address = forms.CharField(label=_("Address"))
    
        class Meta:
            model = User
            fields = (UsernameField(), "email", "contact_number", "contact_address")
    

    【讨论】:

      【解决方案2】:
      So you have two models for user and user_profile. One user one profile 
      so:
      
      Try this:
      #models.py
      class User_profile(models.Model):
      User= models.Foreignkey('User')
      #add more user data
      
      #forms.py
      class UserProfileForm(ModelForm):
      model = User_profile
      fields = ['User']
      
      #views.py
      class SomeView(CreateView):
      form_class = UserProfileForm()
      

      【讨论】:

      • 谢谢丹尼斯。我试过了,但我发现字段 ['User'] 变成了一个选择字段,而不是一个空白的用户名字段。我的要求是同时创建用户和用户的个人资料,但现在您提供的解决方案似乎为现有用户创建用户个人资料。请你再找我看看。非常感谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-16
      • 2015-03-08
      • 2018-11-30
      • 1970-01-01
      • 2013-04-06
      • 2015-07-26
      相关资源
      最近更新 更多