2014-11-23 75 views

回答

1

该视图的dispatch方法是返回HttpResponse的方法。你总是可以提出一个不会在别处处理的异常并在那里捕获它。它应该泡起来,直到它到达那里。

Ex。

#place where you want to raise exception 
if condition.is_not_met: 
    raise WoahException 

#views.py 
class MyFormView(views.FormView): 
    def dispatch(self, request, *args, **kwargs): 
     try: 
      return super(MyFormView, self).dispatch(request, *args, **kwargs) 
     except WoahException: 
      return HttpResponse("Woah, there was an exception") 
+0

完美,谢谢! – arctelix 2014-11-23 08:31:42

+0

我有另一个hickup,事实证明我实际上需要赶上在模板标签中引发的异常。见http://stackoverflow.com/questions/27210643/django-how-to-catch-a-specific-exception-in-a-class-based-view-during-template – arctelix 2014-11-30 07:19:13