好吧,这实际上可能是一个简单的案例,但我很难弄清楚。
我有两个用户注册渠道(公司和其他所有人)。当企业用户通过我的注册表单创建 User 实例时,我还希望他们输入创建相关实例的辅助表单(基于 Website 和 Organization_Contact 模型)。
我知道如何通过发出额外的同步或异步请求来解决这个问题,但我希望用户填写三个表单并一键提交。
我的问题是其他两种形式依赖于用户外键作为字段。我已经将该字段设置为“null=True,blank=True”,这样我就可以在没有外键的情况下验证和保存表单,但我最终想将该键添加到两个模型实例中。
我认为我可以验证这三个表单,保存 UserForm,然后使用模型查询集返回新的 User.id(全部在一个视图中)。然后,我将该 user_id 值添加到其他两个表单字典(WebsiteForm 和 Organization_ContactForm)。
它会这样工作:
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
问题:1)不确定我是否可以保存模型表单,然后在单个视图中将该模型实例作为查询集返回
2)我说我不确定,因为我无法通过尝试将变量传递给查询集的问题。
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.