Redirect any urls to 404.html if not found in urls.py in django

家住魔仙堡 提交于 2019-12-30 18:06:53

问题


How can I redirect any kind of url patterns to a created page "404.html" page if it doesn't exist in the urls.py rather than being shown the error by django.


回答1:


Make a view that'll render your created 404.html and set it as handler404 in urls.py.

handler404 = 'app.views.404_view'

Django will render debug view if debug is enabled. Else it'll render 404 page as specified in handler404 for all types of pages if it doesn't exist.

Django documentation on Customizing error views.

Check this answer for a complete example.




回答2:


In your views.py, just add the following code (No need to change anything in urls.py).

from django.shortcuts import render_to_response
from django.template import RequestContext


def handler404(request):
    response = render_to_response('404.html', {},
                              context_instance=RequestContext(request))
    response.status_code = 404
    return response

Put a custom 404.html in templates directory.

source : click here




回答3:


Go to your project settings.py and set DEBUG = True to DEBUG = False Then Django redirects all NOT set patterns to not found.

In additional if you want to customize 404 template , in your project urls.py

set

handler404 = 'app.views.404_view'

then in your projects view.py

from django.shortcuts import render_to_response
from django.template import RequestContext

def handler404(request):
    response = render_to_response('404.html', {},
                                  context_instance=RequestContext(request))
    response.status_code = 404
    return response

and Finally, in your templates add 404.html and fill it with what you want to show end user.




回答4:


There is no need to change anything in your view or url. Just do these 2 steps, in your settings.py, do the following

DEBUG = False
ALLOWED_HOSTS = ["*"]

And in your app directory (myapp in this example), create myapp/templates/404.html where 404.html is your custom error page. That is it.



来源:https://stackoverflow.com/questions/30228818/redirect-any-urls-to-404-html-if-not-found-in-urls-py-in-django

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