Django, 사용자 지정 500/404 오류 페이지 만들기
여기에 있는 튜토리얼을 정확히 따르면 사용자 지정 500 또는 404 오류 페이지를 만들 수 없습니다. 잘못된 URL을 입력하면 페이지에 기본 오류 페이지가 표시됩니다. 사용자 정의 페이지가 표시되지 않도록 확인해야 할 사항이 있습니까?
파일 디렉토리 :
mysite/
mysite/
__init__.py
__init__.pyc
settings.py
settings.pyc
urls.py
urls.pyc
wsgi.py
wsgi.pyc
polls/
templates/
admin/
base_site.html
404.html
500.html
polls/
detail.html
index.html
__init__.py
__init__.pyc
admin.py
admin.pyc
models.py
models.pyc
tests.py
urls.py
urls.pyc
view.py
views.pyc
templates/
manage.py
mysite / settings.py 내에서 다음을 활성화했습니다.
DEBUG = False
TEMPLATE_DEBUG = DEBUG
#....
TEMPLATE_DIRS = (
'C:/Users/Me/Django/mysite/templates',
)
mysite / polls / urls.py 내에서 :
from django.conf.urls import patterns, url
from polls import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^(?P<poll_id>\d+)/$', views.detail, name='detail'),
url(r'^(?P<poll_id>\d+)/results/$', views.results, name='results'),
url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),
)
필요한 다른 코드를 게시 할 수 있지만 잘못된 URL을 사용하는 경우 사용자 지정 500 오류 페이지를 얻으려면 무엇을 변경해야합니까?
편집하다
솔루션 : 추가로
TEMPLATE_DIRS
내 settings.py 내에서 문제가 발생했습니다.
Under your main views.py
add your own custom implementation of the following two views, and just set up the templates 404.html and 500.html with what you want to display.
With this solution, no custom code needs to be added to urls.py
Here's the code:
from django.shortcuts import render_to_response
from django.template import RequestContext
def handler404(request, *args, **argv):
response = render_to_response('404.html', {},
context_instance=RequestContext(request))
response.status_code = 404
return response
def handler500(request, *args, **argv):
response = render_to_response('500.html', {},
context_instance=RequestContext(request))
response.status_code = 500
return response
Update
handler404
and handler500
are exported Django string configuration variables found in django/conf/urls/__init__.py
. That is why the above config works.
To get the above config to work, you should define the following variables in your urls.py
file and point the exported Django variables to the string Python path of where these Django functional views are defined, like so:
# project/urls.py
handler404 = 'my_app.views.handler404'
handler500 = 'my_app.views.handler500'
Update for Django 2.0
Signatures for handler views were changed in Django 2.0: https://docs.djangoproject.com/en/2.0/ref/views/#error-views
If you use views as above, handler404 will fail with message:
"handler404() got an unexpected keyword argument 'exception'"
In such case modify your views like this:
def handler404(request, exception, template_name="404.html"):
response = render_to_response("404.html")
response.status_code = 404
return response
Official answer:
Here is the link to the official documentation on how to set up custom error views:
https://docs.djangoproject.com/en/stable/topics/http/views/#customizing-error-views
It says to add lines like these in your URLconf (setting them anywhere else will have no effect):
handler404 = 'mysite.views.my_custom_page_not_found_view'
handler500 = 'mysite.views.my_custom_error_view'
handler403 = 'mysite.views.my_custom_permission_denied_view'
handler400 = 'mysite.views.my_custom_bad_request_view'
You can also customise the CSRF error view by modifying the setting CSRF_FAILURE_VIEW
.
Default error handlers:
It's worth reading the documentation of the default error handlers, page_not_found
, server_error
, permission_denied
and bad_request
. By default, they use these templates if they can find them, respectively: 404.html
, 500.html
, 403.html
, and 400.html
.
So if all you want to do is make pretty error pages, just create those files in a TEMPLATE_DIRS
directory, you don't need to edit URLConf at all. Read the documentation to see which context variables are available.
In Django 1.10 and later, the default CSRF error view uses the template 403_csrf.html
.
Gotcha:
Don't forget that DEBUG
must be set to False for these to work, otherwise, the normal debug handlers will be used.
Add these lines in urls.py
urls.py
from django.conf.urls import (
handler400, handler403, handler404, handler500
)
handler400 = 'my_app.views.bad_request'
handler403 = 'my_app.views.permission_denied'
handler404 = 'my_app.views.page_not_found'
handler500 = 'my_app.views.server_error'
# ...
and implement our custom views in views.py.
views.py
from django.shortcuts import (
render_to_response
)
from django.template import RequestContext
# HTTP Error 400
def bad_request(request):
response = render_to_response(
'400.html',
context_instance=RequestContext(request)
)
response.status_code = 400
return response
# ...
From the page you referenced:
When you raise Http404 from within a view, Django will load a special view devoted to handling 404 errors. It finds it by looking for the variable handler404 in your root URLconf (and only in your root URLconf; setting handler404 anywhere else will have no effect), which is a string in Python dotted syntax – the same format the normal URLconf callbacks use. A 404 view itself has nothing special: It’s just a normal view.
So I believe you need to add something like this to your urls.py:
handler404 = 'views.my_404_view'
and similar for handler500.
If all you need is to show custom pages which have some fancy error messages for your site when DEBUG = False
, then add two templates named 404.html and 500.html in your templates directory and it will automatically pick up this custom pages when a 404 or 500 is raised.
settings.py::::
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ALLOWED_HOSTS = ['localhost'] #provide your host name
and just add your 404.html and 500.html pages in templates folder. remove 404.html and 500.html from templates in polls app.
In Django 2.* you can use this construction in views.py
def handler404(request, exception):
return render(request, 'errors/404.html', locals())
In settings.py
DEBUG = False
if DEBUG is False:
ALLOWED_HOSTS = [
'127.0.0.1:8000',
'*',
]
if DEBUG is True:
ALLOWED_HOSTS = []
In urls.py
# https://docs.djangoproject.com/en/2.0/topics/http/views/#customizing-error-views
handler404 = 'YOUR_APP_NAME.views.handler404'
Usually i creating default_app and handle site-wide errors, context processors in it.
Make an error, On the error page find out from where django is loading templates.I mean the path stack.In base template_dir add these html pages 500.html , 404.html. When these errors occur the respective template files will be automatically loaded.
You can add pages for other error codes too, like 400 and 403.
Hope this help !!!
As one single line (for 404 generic page):
from django.shortcuts import render_to_response
from django.template import RequestContext
return render_to_response('error/404.html', {'exception': ex},
context_instance=RequestContext(request), status=404)
# views.py
def handler404(request, exception):
context = RequestContext(request)
err_code = 404
response = render_to_response('404.html', {"code":err_code}, context)
response.status_code = 404
return response
# <project_folder>.urls.py
handler404 = 'todo.views.handler404'
This works on django 2.0
Be sure to include your custom 404.html
inside the app templates folder.
Try moving your error templates to .../Django/mysite/templates/
?
I'm note sure about this one, but i think these need to be "global" to the website.
참고URL : https://stackoverflow.com/questions/17662928/django-creating-a-custom-500-404-error-page
'developer tip' 카테고리의 다른 글
날짜 문자열 또는 개체의 NSArray 정렬 (0) | 2020.09.20 |
---|---|
Gradle 인수에 대한 compile () 메서드를 찾을 수 없습니다. (0) | 2020.09.20 |
확장 방법의 장점은 무엇입니까? (0) | 2020.09.20 |
<0xEF, 0xBB, 0xBF> 문자가 파일에 표시됩니다. (0) | 2020.09.20 |
파일 시스템에서 클래스를 이동 한 후 "XXX 클래스는 유효한 엔티티 또는 매핑 된 수퍼 클래스가 아닙니다." (0) | 2020.09.20 |