Django 通过消息引发 404

标签 django django-forms django-views

我喜欢在脚本中的不同位置引发 404 错误消息,例如:Http404("some error msg: %s"%msg) 因此,在我的 urls.py 中我包括:

handler404 = Custom404.as_view()

任何人都可以告诉我应该如何处理我的观点中的错误。我对 Django 还很陌生,所以一个例子会有很大帮助。
非常感谢。

最佳答案

通常 404 错误中不应该有任何自定义消息,但如果您想实现它,可以使用 django 中间件来实现。

中间件

from django.http import Http404, HttpResponse


class Custom404Middleware(object):
    def process_exception(self, request, exception):
        if isinstance(exception, Http404):
            # implement your custom logic. You can send
            # http response with any template or message
            # here. unicode(exception) will give the custom
            # error message that was passed.
            msg = unicode(exception)
            return HttpResponse(msg, status=404)

中间件设置

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'college.middleware.Custom404Middleware',
    # Uncomment the next line for simple clickjacking protection:
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

这样就可以了。如果我做错了什么,请纠正我。希望这会有所帮助。

关于Django 通过消息引发 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16367374/

相关文章:

Django按相关领域排序

django - 在 Django 中,如何执行以下多对多查询(使用直通表)?

具有多个外键的 Django 内联表单

python - 以 django 形式强制

python - Django 查看相同 url 模式请求的执行顺序?

python - django.core.urlresolver.reverse - NoReverseMatch : Reverse for '...' with arguments '()' and keyword arguments '{}' not found

ios - 从 App Store 下载的应用程序有 BadDeviceToken,从源代码构建没有

python - 将主键放在 JSON 响应中

python - wrapper() 得到了一个意外的关键字参数 'id'

Django 表单字段分组