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



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

用户配置文件

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

地址

  1. 城市
  2. .ZIP

我的问题是,如果我只想将一个注册表和一个模板保存到这两个模型中,我将如何完成? **我正在使用 Django@1.5.4

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上有一个UserProfile外键字段,并且您已经为模型创建了继承自ModelForm的上述类。

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

Django 视图不限制你可以尝试从 request.POST 中的数据中水化的表单类的数量。

最新更新