How to properly setup custom handler404 in django?

匆匆过客 提交于 2019-12-22 03:23:02

问题


According to the documentation this should be fairly simple: I just need to define handler404. Currently I am doing, in my top urls.py:

urlpatterns = [
    ...
]

handler404 = 'myapp.views.handle_page_not_found'

The application is installed. The corresponding view is just (for the time being I just want to redirect to the homepage in case of 404):

def handle_page_not_found(request):
    return redirect('homepage')

But this has no effect: the standard (debug) 404 page is shown.

The documentation is a bit ambiguous:

  • where should handler404 be defined? The documentation says in the URLconf but, where exactly? I have several applications, each with a different urls.py. Can I put it in any of them? In the top URLconf? Why? Where is this documented?
  • what will be catched by this handler? Will it catch django.http.Http404, django.http.HttpResponseNotFound, django.http.HttpResponse (with status=404)?

回答1:


As we discussed, your setup is correct, but in settings.py you should make DEBUG=False. It's more of a production feature and won't work in development environment(unless you have DEBUG=False in dev machine of course).




回答2:


Debug should be False and add to view *args and **kwargs. Add to urls.py handler404 = 'view_404'

def view_404(request, *args, **kwargs):
return redirect('https://your-site/404')

If I didn't add args and kwargs server get 500.




回答3:


To render 404 Error responses on a custom page, do the following:

In your project directory open settings.py and modify DEBUG as follows:

    DEBUG = False

In the same directory create a file and name it views.py, insert the following code:

   from django.shortcuts import render

   def handler404(request, exception):
       return render(request, 'shop/shop.html')

Finally open urls.py file which is in the same project directory and add the following code:

   from django.contrib import admin
   from . import views

   handler404 = views.handler404

   urlpatterns = [
      path('admin/', admin.site.urls),
   ]


来源:https://stackoverflow.com/questions/35156134/how-to-properly-setup-custom-handler404-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!