Several of Django’s built-in views are documented in Writing views as well as elsewhere in the documentation.
Serving files in development¶
There may be files other than your project’s static assets that, for convenience, you’d like to have Django serve for you in local development. The serve() view can be used to serve any directory you give it. (This view is not hardened for production use and should be used only as a development aid; you should serve these files in production using a real front-end web server).
The most likely example is user-uploaded content in MEDIA_ROOT . django.contrib.staticfiles is intended for static assets and has no built-in handling for user-uploaded files, but you can have Django serve your MEDIA_ROOT by appending something like this to your URLconf:
Note, the snippet assumes your MEDIA_URL has a value of ‘/media/’ . This will call the serve() view, passing in the path from the URLconf and the (required) document_root parameter.
Since it can become a bit cumbersome to define this URL pattern, Django ships with a small URL helper function static() that takes as parameters the prefix such as MEDIA_URL and a dotted path to a view, such as ‘django.views.static.serve’ . Any other function parameter will be transparently passed to the view.
Error views¶
The 404 (page not found) view¶
When you raise Http404 from within a view, Django loads a special view devoted to handling 404 errors. By default, it’s the view django.views.defaults.page_not_found() , which either produces a very simple “Not Found” message or loads and renders the template 404.html if you created it in your root template directory.
The default 404 view will pass two variables to the template: request_path , which is the URL that resulted in the error, and exception , which is a useful representation of the exception that triggered the view (e.g. containing any message passed to a specific Http404 instance).
Three things to note about 404 views:
- The 404 view is also called if Django doesn’t find a match after checking every regular expression in the URLconf.
- The 404 view is passed a RequestContext and will have access to variables supplied by your template context processors (e.g. MEDIA_URL ).
- If DEBUG is set to True (in your settings module), then your 404 view will never be used, and your URLconf will be displayed instead, with some debug information.
The 500 (server error) view¶
Similarly, Django executes special-case behavior in the case of runtime errors in view code. If a view results in an exception, Django will, by default, call the view django.views.defaults.server_error , which either produces a very simple “Server Error” message or loads and renders the template 500.html if you created it in your root template directory.
The default 500 view passes no variables to the 500.html template and is rendered with an empty Context to lessen the chance of additional errors.
If DEBUG is set to True (in your settings module), then your 500 view will never be used, and the traceback will be displayed instead, with some debug information.
The 403 (HTTP Forb > defaults. permission_denied (request, exception, template_name=’403.html’)¶
In the same vein as the 404 and 500 views, Django has a view to handle 403 Forb > django.views.defaults.permission_denied .
This view loads and renders the template 403.html in your root template directory, or if this file does not exist, instead serves the text “403 Forb > RFC 7231#section-6.5.3 (the HTTP 1.1 Specification). The template context contains exception , which is the string representation of the exception that triggered the view.
django.views.defaults.permission_denied is triggered by a PermissionDenied exception. To deny access in a view you can use code like this:
The 400 (bad request) view¶
When a SuspiciousOperation is raised in Django, it may be handled by a component of Django (for example resetting the session data). If not specifically handled, Django will consider the current request a ‘bad request’ instead of a server error.
django.views.defaults.bad_request , is otherwise very similar to the server_error view, but returns with the status code 400 indicating that the error condition was the result of a client operation. By default, nothing related to the exception that triggered the view is passed to the template context, as the exception message might contain sensitive information like filesystem paths.
bad_request views are also only used when DEBUG is False .
I have made a simple django application for creating my custom 404 page using django 1.10. I have created 404.html and 500.html in my page,According to Django Documentation.Then I tried two methods to render the 404 Error message.
1)I made simple 404.html and 500.html page and did nothing then. I was successful in getting the 500 page. Correct url to the page was:localhost:8000/book And I supplied localhost:8000/book/fgfg And there was no entry according to the input.But it was sending me to the 500 page but not to the 404 page as I expected. This is Internal App’s Urls.py:
And this is External Project’s urls.py:
I have commented the handler404 and 500 here which I uncommented in 2nd method. In first method I d t match any of these.
And If I set DEBUG=FALSE It resulted into 500 error.
2)Now in method 2: I updated the views.py file and Uncommented the handler404 and handler505 line from urls.py.
This is views.py:
Again I was getting the 500 Page.I tried to delete the 500 and Debug=False then It resulted into 500.Then I turned debug on,It was saying the error was a 404 error. So whatever I did,I got a 500.html page called. Now I am confused how to load 404.html page correctly.
Решил создать кастомную страницу для ошибок в Django
в settings прописал
В главном urls (есть еще отдельное приложение blog, со своим urls, в нем же хранится templates и статика для 404 страницы, а так же view который отображает все это)
и под urlpaterns прописал вот это
ну и такое views
Странность следующая,
в моей странице ошибки (которая одинаково отображется для всех ошибок) подключаются бутстрап стили и картинка,
картинку я добавил в проект день назад, но прикол в том, что django видит и отображет только старые файлы, например бутстрап был с самого начала и он подключается или если отобразить старые картинки тоже, любое что я добавлю в папку с картинками или стилями, не отображется и django этого не видит, хотя оно там есть, что за ерунда? Но если подключить что-то внешнее, грузить картинку из интернета, то все ок