【问题标题】:exceptions must be old-style classes or derived from BaseException, not HttpResponseRedirect异常必须是旧式类或派生自 BaseException,而不是 HttpResponseRedirect
【发布时间】:2016-02-25 05:31:59
【问题描述】:

这个错误是什么意思?我正在导入from django.shortcuts import render, Http404, HttpResponseRedirect ,但为什么不能使用 HttpResponseRedirect?我读了回溯,但那里没有什么用处...... 这是我的代码

@login_required
def read(request, id):
    try:
        next = request.GET.get('next', None)
        notification = Notification.objects.get(id=id)
        if notification.recipient == request.user:
            notification.read = True
            notification.save()
            if next is not None:
                return HttpResponseRedirect(next)
            else:
                return HttpResponseRedirect(reverse("notifications_all"))
        else:
            raise Http404
    except:
        raise HttpResponseRedirect(reverse("notifications_all"))

我不明白错误的含义,有人可以向我解释我做错了什么吗?

【问题讨论】:

    标签: python django


    【解决方案1】:

    在这一行:

    except:
        raise HttpResponseRedirect(reverse("notifications_all"))
    

    回溯告诉您不能raise HttpResponseRedirect(...),因为这不是继承自BaseExceptionException

    您可能想要做的是在这里改用return 或替代raise a 404?

    【讨论】:

    • 顺便说一句,你介意看看这个吗?stackoverflow.com/questions/35478137/... 我已经为此苦苦挣扎了一段时间。
    • 我试了一下。我认为 Traceback 让您有些失望,因为消息传递的信息量不是很大。一般来说,你应该更仔细地阅读 Tracebacks,我的意思是,整个事情。查找应用程序中发生错误的位置。 Python 有漂亮而有用的 Tracebacks。
    【解决方案2】:

    HttpResponseRedirect 也不例外,而是一个返回重定向的django函数。

    由于它可能令人困惑,您可能希望使用渲染:

    from django.shortcuts import redirect
    
    ...
    
         if next is not None:
           return redirect(next)
         else:
           return redirect(reverse("notifications_all"))
    

    【讨论】:

    猜你喜欢
    • 2018-11-21
    • 2012-07-14
    • 2016-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-05
    • 2021-10-31
    相关资源
    最近更新 更多