为了注册,我需要下列按模型分组的字段:
UserProfile
地址
我的问题是,如果我只想有一个登记表和一个模板来保存到这两个模型中,我将如何做到这一点?**我正在使用Django@1.5.4
发布于 2013-10-21 18:18:08
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中的数据中水合物的表单类的数量。
https://stackoverflow.com/questions/19501639
复制相似问题