首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将用户信息注册到各种django模型

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

Stack Overflow用户
提问于 2013-10-21 18:07:58
回答 1查看 57关注 0票数 0

为了注册,我需要下列按模型分组的字段:

UserProfile

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

地址

  1. 街道
  2. 城市
  3. ZIP
  4. 状态

我的问题是,如果我只想有一个登记表和一个模板来保存到这两个模型中,我将如何做到这一点?**我正在使用Django@1.5.4

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-10-21 18:18:08

代码语言:javascript
运行
复制
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})

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

当然,无意冒犯,但是粗略地看一下Django教程会给您一个很好的开始来回答这个问题。仔细阅读模型和queryset API文档也是一个很好的起点。

Django视图没有限制您可以尝试从request.POST中的数据中水合物的表单类的数量。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19501639

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档