Django:同时保存多个模型(复杂情况) [英] Django: saving multiple modelforms simultaneously (complex case)

查看:179
本文介绍了Django:同时保存多个模型(复杂情况)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗯,实际上可能是一个简单的例子,但是我很难想出来。



我有两个用户注册漏洞(公司和其他人)。当公司用户通过我的注册表单创建User实例时,我也希望他们输入创建相关实例的二级表单(基于Website和Organization_Contact模型)。



我知道如何通过进行其他同步或异步请求来解决这个问题,但是我希望用户填写三个表单并点击一次提交。



我的问题是其他两种形式依赖于用户外键作为字段。我使该字段null = True,blank = True,以便我可以验证和保存没有外键的表单,但我最终要将该键添加到两个模型实例。



我以为我可以验证三种形式,保存UserForm,然后使用模型查询器返回新的User.id(全部在一个视图中)。然后我将该user_id值添加到其他两个表单字典(WebsiteForm和Organization_ContactForm)。



它可以这样工作:

  def register_company(request) :
如果request.method =='POST'
uform = UserCreationForm(request.POST,prefix ='user')
sform = SiteForm(request.POST,prefix ='site')
oform = OrgForm(request.POST,prefix ='site')
如果uform.is_valid()和sform.is_valid()和oform.is_valid():
uform.save()
user = User.objects.get(email__iexact = uform.cleaned_data ['email'])
uid = unicode(user.id)
#知道我会将uid添加回SiteForm和Orgform字典,然后保存两个实例

问题:
1)不知道我是否可以保存模型,然后在一个视图中将该模型实例作为查询集返回



2)我说我不确定,因为我无法传递问题试图将变量传递给查询器。



获取管理器方法似乎不接受一个变量。我假设,因为我通过了一个等效的硬编码字符串,它的工作。



好的,所以我正在考虑创建一个新的管理器方法(电子邮件),接受一个变量参数(清理的电子邮件字段),然后重试保存一个模型,检索模型ID数据,并保存其他模型。



我还以为我可以通过邮寄保存信号来处理这个问题。



这里的一般方向真的很有帮助。我需要一个起点



谢谢!

解决方案

ModelForm s?

  if request.method =='POST'
uform = UserCreationForm(request.POST,prefix ='user')
sform = SiteForm(request.POST,prefix ='site')
oform = OrgForm(request.POST,prefix ='网站')
如果uform.is_valid()和sform.is_valid()和oform.is_valid():
#save返回对象
user = uform.save()

#commit = false不保存到DB。
site = sform.save(commit = False)
site.user = user
site.save()

org = oform.save(commit = False)
org.user = user
org.save()

有关评论的更新:为什么在一个地方可以将这个表单传播到多个区域和文件(信号,表单保存)中?



代码更可读,甚至可以保存代码行。除非它将在全球范围内使用。


Well, it may actually be a simple case but I'm having a tough time figuring it out.

I have two user registration funnels (corporate & everyone else). When a corporate user creates a User instance through my registration form, I would also like them to input secondary forms that create related instances (based on the Website and Organization_Contact models).

I know how to solve this by making additional synchronous or asynchronous requests, but I'd like the user to fill out the three forms and submit with one click.

My issue here is that the other two forms rely on a User foreign key as a field. I've made that field "null=True, blank=True" so that I can validate and save the forms without the foreign key, but I ultimately want to add that key to both model instances.

I thought that I could validate the three forms, save the UserForm, and then use a model queryset to return the new User.id (all in one view). I would then add that user_id value to the other two form dictionaries (WebsiteForm and Organization_ContactForm).

It would work as so:

def register_company(request):
    if request.method=='POST'
       uform=UserCreationForm(request.POST, prefix='user')
       sform=SiteForm(request.POST, prefix='site')
       oform=OrgForm(request.POST, prefix='site')
       if uform.is_valid() and sform.is_valid() and oform.is_valid():
            uform.save()
            user=User.objects.get(email__iexact=uform.cleaned_data['email'])
            uid=unicode(user.id)
       #now I'd add uid back into the SiteForm and Orgform dictionaries and then save both instances              

Problems: 1) Not sure if I can save a modelform and then return that model instance as a queryset in a single view

2)I say that I'm not sure because I couldn't get passed the problem of trying to pass a variable to the queryset.

The get manager method seems to not accept a variable there. I assume as much because I passed an equivalent hardcoded string and it worked.

Ok, so I was thinking about creating a new manager method (email) which accepted a variable argument (the cleaned email field) and then retrying the process of saving one modelform, retrieving the model id data, and saving the other modelforms.

I also thought that I might be able to handle this issue through a post save signal.

Just general direction here would be really helpful. I need a starting point

Thanks!

解决方案

Are these all ModelForms?

if request.method=='POST'
   uform=UserCreationForm(request.POST, prefix='user')
   sform=SiteForm(request.POST, prefix='site')
   oform=OrgForm(request.POST, prefix='site')
   if uform.is_valid() and sform.is_valid() and oform.is_valid():
        # save returns the object 
        user = uform.save()

        # commit = false doesn't save to DB.
        site = sform.save(commit=False)
        site.user = user
        site.save()

        org = oform.save(commit=False)
        org.user = user
        org.save()

Update regarding comments: Why spread this form saving logic around into multiple areas and files (signals, form save) when you can do it in one place?

The code is more readable, and you even save lines of code. Unless it's going to be used globally.

这篇关于Django:同时保存多个模型(复杂情况)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆