对于注册,我需要按模型分组的以下字段:
用户配置文件
- 全名
- 出生日期
- 职业
地址
- 街
- 城市
- .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 中的数据中水化的表单类的数量。