将用户信息注册到各种django型号

时间:2013-10-21 18:07:58

标签: django django-models django-forms django-templates

对于注册,我需要按模型分组以下字段:

用户配置

  1. 全名
  2. 出生日期
  3. 职业
  4. 地址

    1. ZIP
    2. 国家
    3. 我的问题是,如果我只想要一个注册表单和一个模板来保存这两个模型,我将如何完成这项工作? **我正在使用Django@1.5.4

1 个答案:

答案 0 :(得分:1)

from your app.forms import UserProfileForm, AddressForm


def your_view(request):
    user_profile_form = UserProfileForm(request.POST or None)
    address_form = AddressForm(request.POST or None)

    if user_profile_form.is_valid() and address_form.is_valid():
        # creates and returns the new object, persisting it to the database
        user_profile = user_profile_form.save()

        # creates but does not persist the object
        address = AddressForm.save(commit=False)

        # assigns the foreign key relationship
        address.user_profile = user_profile

        # persists the Address model
        address.save()

    return render(request, 'your-template.html',
        {'user_profile_form': user_profile_form,
        'address_form': address_form})

上述代码假设UserProfile上有Address个外键字段,并且您已为模型创建了继承自ModelForm的上述类。

当然没有冒犯,但粗略地浏览一下Django教程应该会给你一个很好的开始回答这个问题。仔细阅读模型和查询集API文档也是一个很好的起点。

Django视图不会限制您可以尝试从request.POST中的数据进行水合的表单类的数量。