我需要返回一个render_to_response,以防我的FormView派生类中发生异常。 我正在做以下(代码摘录,但代码的其余部分不会导致问题):
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数据库会话数据引起的。
我做错了什么?我应该在通用视图中以不同方式使用render_to_response吗?
答案 0 :(得分:0)
我不知道发生了什么,但我已经解决了一个解决方法:
dummy = self.request.user.is_authenticated()
在返回render_to_response之前调用is_authenticated解决问题,因为request.user被“转换”到实际的用户实例,而不是保留SimpleLazyObject。
我希望了解为什么有一天会发生......