【问题标题】:Is there a way to force an immidiate HttpResponse from a class based FormView method (eg. get_initial)?有没有办法从基于类的 FormView 方法(例如 get_initial)强制立即 HttpResponse?
【发布时间】:2014-11-23 05:58:18
【问题描述】:

有没有办法从基于类的视图方法中强制立即HttpResponse

例如,如果在get_initial 或任何其他视图方法中出现异常,我们是否可以强制视图停止表单呈现过程并发送HttpResponse

【问题讨论】:

    标签: django django-class-based-views


    【解决方案1】:

    视图的dispatch 方法返回一个HttpResponse。您总是可以引发一个不会在其他地方处理的异常并在那里捕获它。它应该只是冒泡,直到它到达那里。

    例如。

    #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")
    

    【讨论】:

    猜你喜欢
    • 2015-05-31
    • 2014-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-06
    • 2014-03-22
    • 1970-01-01
    相关资源
    最近更新 更多