1

如果在我的 FormView 派生类中发生异常,我需要返回一个 render_to_response。我正在执行以下操作(代码摘录,但其余代码不会引起问题):

class ProjectCreateView(FormView):
    """Create view."""

    form_class = ProjectCreateForm
    template_name = 'projects/project_form.html'
    group = None

    def dispatch(self, request, *args, **kwargs):
        """Populate group attribute."""

        self.group = get_object_or_404(Group, slug=self.kwargs['slug'])
        return super(ProjectCreateView, self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        """Add current group to context."""

        context = super(ProjectCreateView, self).get_context_data(**kwargs)
        context['group'] = self.group
        return context

    def form_valid(self, form):
        """Form and logic behind project creation."""

        project_file = form.cleaned_data['project_file']
        thumbnail = form.cleaned_data['thumbnail']
        description = form.cleaned_data['description']

        try:
            <something to try>
        except IntegrityError as e:
            data = {'error':{'msg':_('project_overwrite_error')}}
            return render_to_response('generic_error.html',data,context_instance=RequestContext(self.request))
        except Exception as e:
            return HttpResponse(e)

    return HttpResponseRedirect(self.group.get_absolute_url())

如果我在 dispatch() 方法中使用断点进行调试,一切正常,并且我的错误模板已正确加载,上下文处理器也可以正常工作。当我在调试之外运行它时,我得到一个 DatabaseError,这似乎是由对 django DB 会话数据的访问引起的。

我究竟做错了什么?我应该在通用视图中以不同的方式使用 render_to_response 吗?

4

1 回答 1

0

我不知道发生了什么,但我已经解决了一个解决方法:

dummy = self.request.user.is_authenticated()

在返回 render_to_response 之前调用 is_authenticated 可以解决问题,因为 request.user 被“投射”到实际的用户实例,而不是保留一个 SimpleLazyObject。

我希望有一天能明白为什么会发生这种情况......

于 2013-09-06T16:15:18.663 回答