【问题标题】:Django Form Preview - Adding the User to the Form before saveDjango 表单预览 - 保存前将用户添加到表单
【发布时间】:2009-03-09 10:57:38
【问题描述】:
class RegistrationFormPreview(FormPreview):
    preview_template    = 'workshops/workshop_register_preview.html'
    form_template       = 'workshops/workshop_register_form.html'

    def done(self, request, cleaned_data):
        # Do something with the cleaned_data, then redirect
        # to a "success" page. 
        # data = request.POST.copy()
        # data['user_id'] = u'%s' % (request.user.id)
        # cleaned_data['user'] = u'%s' % (request.user.id)
        #f = self.form(cleaned_data)
        #f = self.form(data)
        #f.user = request.user


        f = self.form(request.POST)
        f.save()

        pdb.set_trace()
        return HttpResponseRedirect('/register/success')

如您所见,我尝试了几种方法,但已被注释掉。任务显然很简单:在保存之前将用户从请求添加到表单,然后保存。

这里接受的工作方法是什么?

【问题讨论】:

    标签: django-forms


    【解决方案1】:

    如果无法修改用户,我会说它甚至不应该首先包含在表单中。

    无论哪种方式,using the commit argument 都可以防止立即保存生成的对象(假设FormPreview 使用ModelForm):

    obj = form.save(commit=False)
    obj.user = request.user
    obj.save()
    

    【讨论】:

    • 感谢 insin,继续!如果您想继续,我还有一个相关的问题:stackoverflow.com/questions/628132/…best thx。
    • @insin 如果obj.save() 引发错误会怎样?大多数情况下,简单的request.user 案例可能并非如此,但更复杂的案例呢? save(commit=False) 之后如何处理验证和错误渲染
    猜你喜欢
    • 2017-12-26
    • 2020-11-10
    • 1970-01-01
    • 1970-01-01
    • 2014-08-26
    • 2020-10-16
    • 1970-01-01
    • 2012-01-27
    • 2019-05-25
    相关资源
    最近更新 更多