Django:同时保存多个模型(复杂情况)

发布于 2024-10-18 05:00:54 字数 1321 浏览 1 评论 0原文

嗯,这实际上可能是一个简单的案例,但我很难弄清楚。

我有两个用户注册渠道(公司和其他人)。当企业用户通过我的注册表单创建用户实例时,我还希望他们输入创建相关实例的辅助表单(基于网站和 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)我说我不确定,因为我无法解决尝试将变量传递给查询集。

get 管理器方法似乎不接受那里的变量。我这么假设是因为我传递了一个等效的硬编码字符串并且它起作用了。

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

我还认为我也许可以通过保存后信号来处理这个问题。

这里只要有大致的指导就会非常有帮助。我需要一个起点。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

橘和柠 2024-10-25 05:00:54

这些都是 ModelForm 吗?

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()

关于评论的更新:当您可以在一个地方完成此操作时,为什么要将这种表单保存逻辑分散到多个区域和文件(信号、表单保存)中?

代码更具可读性,甚至可以节省代码行。除非它要在全球范围内使用。

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.

不回头走下去 2024-10-25 05:00:54

我就是这样做的:

def register_company(request):
    uform=UserCreationForm(request.POST or None, prefix='user')
    sform=SiteForm(request.POST or None, prefix='site')
    oform=OrgForm(request.POST or None, prefix='site')

    if request.POST and all((uform.is_valid(), sform.is_valid(), oform.is_valid()):
        user = uform.save()
        sform.save(user)
        oform.save(user)

    ruturn ...

class UserCreateionForm(ModelForm):
    Meta:
        model = User

class SiteForm(ModelForm):
    Meta:
        model=Site
        exclude=['user', ]

    def save(self, user, commit=True):
        self.instance.user = user
        return super(SiteForm, self).save(commit=commit)

This is how I would do it:

def register_company(request):
    uform=UserCreationForm(request.POST or None, prefix='user')
    sform=SiteForm(request.POST or None, prefix='site')
    oform=OrgForm(request.POST or None, prefix='site')

    if request.POST and all((uform.is_valid(), sform.is_valid(), oform.is_valid()):
        user = uform.save()
        sform.save(user)
        oform.save(user)

    ruturn ...

class UserCreateionForm(ModelForm):
    Meta:
        model = User

class SiteForm(ModelForm):
    Meta:
        model=Site
        exclude=['user', ]

    def save(self, user, commit=True):
        self.instance.user = user
        return super(SiteForm, self).save(commit=commit)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文