Django raising 404 with a message

2020-03-17 03:59发布

I like to raise 404 with some error message at different places in the script eg: Http404("some error msg: %s" %msg) So, in my urls.py I included:

handler404 = Custom404.as_view()

Can anyone please tell me how should I be handling the error in my views. I'm fairly new to Django, so an example would help a lot.
Many thanks in advance.

9条回答
再贱就再见
2楼-- · 2020-03-17 04:19

Yes we can show specific exception message when raise Http404.

Pass some exception message like this

raise Http404('Any kind of message ')

Add 404.html page into templates directory.

templates/404.html

{{exception}}
查看更多
兄弟一词,经得起流年.
3楼-- · 2020-03-17 04:20

You can return a plain HttpResponse object with a status code (in this case 404)

from django.shortcuts import render_to_response

def my_view(request):
    template_context = {}

    # ... some code that leads to a custom 404

    return render_to_response("my_template.html", template_context, status=404)
查看更多
▲ chillily
4楼-- · 2020-03-17 04:20

The default 404 handler calls 404.html . You could edit that if you don't need anything fancy or can override the 404 handler by setting the handler404 view -- see more here

查看更多
兄弟一词,经得起流年.
5楼-- · 2020-03-17 04:24

In general, 404 error is "page not found" error - it should not have customizable messages, simply because it should be raised only when a page is not found.

You can return a TemplateResponse with status parameter set to 404

查看更多
小情绪 Triste *
6楼-- · 2020-03-17 04:32

Raise an Http404 exception inside a view. It's usually done when you catch a DoesNotExist exception. For example:

from django.http import Http404

def article_view(request, slug):
    try:
        entry = Article.objects.get(slug=slug)
    except Article.DoesNotExist:
        raise Http404()
    return render(request, 'news/article.html', {'article': entry, })

Even better, use get_object_or_404 shortcut:

from django.shortcuts import get_object_or_404

def article_view(request):
    article = get_object_or_404(MyModel, pk=1)
    return render(request, 'news/article.html', {'article': entry, })

If you'd like to customize the default 404 Page not found response, put your own template called 404.html to the templates folder.

查看更多
走好不送
7楼-- · 2020-03-17 04:34

Generally there should not be any custom messages in 404 errors bu if you want to implement it you can do this using django middlewares.

Middleware

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)

Middlewares Settings

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',
)

This will do the trick. Correct me if I am doing any thing wrong. Hope this helps.

查看更多
登录 后发表回答