2
0

views.txt 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. ==============
  2. Built-in Views
  3. ==============
  4. .. module:: django.views
  5. :synopsis: Django's built-in views.
  6. Several of Django's built-in views are documented in
  7. :doc:`/topics/http/views` as well as elsewhere in the documentation.
  8. Serving files in development
  9. ============================
  10. .. function:: static.serve(request, path, document_root, show_indexes=False)
  11. There may be files other than your project's static assets that, for
  12. convenience, you'd like to have Django serve for you in local development.
  13. The :func:`~django.views.static.serve` view can be used to serve any directory
  14. you give it. (This view is **not** hardened for production use and should be
  15. used only as a development aid; you should serve these files in production
  16. using a real front-end web server).
  17. The most likely example is user-uploaded content in :setting:`MEDIA_ROOT`.
  18. ``django.contrib.staticfiles`` is intended for static assets and has no
  19. built-in handling for user-uploaded files, but you can have Django serve your
  20. :setting:`MEDIA_ROOT` by appending something like this to your URLconf::
  21. from django.conf import settings
  22. from django.urls import re_path
  23. from django.views.static import serve
  24. # ... the rest of your URLconf goes here ...
  25. if settings.DEBUG:
  26. urlpatterns += [
  27. re_path(
  28. r"^media/(?P<path>.*)$",
  29. serve,
  30. {
  31. "document_root": settings.MEDIA_ROOT,
  32. },
  33. ),
  34. ]
  35. Note, the snippet assumes your :setting:`MEDIA_URL` has a value of
  36. ``'media/'``. This will call the :func:`~django.views.static.serve` view,
  37. passing in the path from the URLconf and the (required) ``document_root``
  38. parameter.
  39. Since it can become a bit cumbersome to define this URL pattern, Django
  40. ships with a small URL helper function :func:`~django.conf.urls.static.static`
  41. that takes as parameters the prefix such as :setting:`MEDIA_URL` and a dotted
  42. path to a view, such as ``'django.views.static.serve'``. Any other function
  43. parameter will be transparently passed to the view.
  44. .. _error-views:
  45. Error views
  46. ===========
  47. Django comes with a few views by default for handling HTTP errors. To override
  48. these with your own custom views, see :ref:`customizing-error-views`.
  49. .. _http_not_found_view:
  50. The 404 (page not found) view
  51. -----------------------------
  52. .. function:: defaults.page_not_found(request, exception, template_name='404.html')
  53. When you raise :exc:`~django.http.Http404` from within a view, Django loads a
  54. special view devoted to handling 404 errors. By default, it's the view
  55. :func:`django.views.defaults.page_not_found`, which either produces a "Not
  56. Found" message or loads and renders the template ``404.html`` if you created it
  57. in your root template directory.
  58. The default 404 view will pass two variables to the template: ``request_path``,
  59. which is the URL that resulted in the error, and ``exception``, which is a
  60. useful representation of the exception that triggered the view (e.g. containing
  61. any message passed to a specific ``Http404`` instance).
  62. Three things to note about 404 views:
  63. * The 404 view is also called if Django doesn't find a match after
  64. checking every regular expression in the URLconf.
  65. * The 404 view is passed a :class:`~django.template.RequestContext` and
  66. will have access to variables supplied by your template context
  67. processors (e.g. ``MEDIA_URL``).
  68. * If :setting:`DEBUG` is set to ``True`` (in your settings module), then
  69. your 404 view will never be used, and your URLconf will be displayed
  70. instead, with some debug information.
  71. .. _http_internal_server_error_view:
  72. The 500 (server error) view
  73. ---------------------------
  74. .. function:: defaults.server_error(request, template_name='500.html')
  75. Similarly, Django executes special-case behavior in the case of runtime errors
  76. in view code. If a view results in an exception, Django will, by default, call
  77. the view ``django.views.defaults.server_error``, which either produces a
  78. "Server Error" message or loads and renders the template ``500.html`` if you
  79. created it in your root template directory.
  80. The default 500 view passes no variables to the ``500.html`` template and is
  81. rendered with an empty ``Context`` to lessen the chance of additional errors.
  82. If :setting:`DEBUG` is set to ``True`` (in your settings module), then
  83. your 500 view will never be used, and the traceback will be displayed
  84. instead, with some debug information.
  85. .. _http_forbidden_view:
  86. The 403 (HTTP Forbidden) view
  87. -----------------------------
  88. .. function:: defaults.permission_denied(request, exception, template_name='403.html')
  89. In the same vein as the 404 and 500 views, Django has a view to handle 403
  90. Forbidden errors. If a view results in a 403 exception then Django will, by
  91. default, call the view ``django.views.defaults.permission_denied``.
  92. This view loads and renders the template ``403.html`` in your root template
  93. directory, or if this file does not exist, instead serves the text
  94. "403 Forbidden", as per :rfc:`9110#section-15.5.4` (the HTTP 1.1
  95. Specification). The template context contains ``exception``, which is the
  96. string representation of the exception that triggered the view.
  97. ``django.views.defaults.permission_denied`` is triggered by a
  98. :exc:`~django.core.exceptions.PermissionDenied` exception. To deny access in a
  99. view you can use code like this::
  100. from django.core.exceptions import PermissionDenied
  101. def edit(request, pk):
  102. if not request.user.is_staff:
  103. raise PermissionDenied
  104. # ...
  105. .. _http_bad_request_view:
  106. The 400 (bad request) view
  107. --------------------------
  108. .. function:: defaults.bad_request(request, exception, template_name='400.html')
  109. When a :exc:`~django.core.exceptions.SuspiciousOperation` is raised in Django,
  110. it may be handled by a component of Django (for example resetting the session
  111. data). If not specifically handled, Django will consider the current request a
  112. 'bad request' instead of a server error.
  113. ``django.views.defaults.bad_request``, is otherwise very similar to the
  114. ``server_error`` view, but returns with the status code 400 indicating that
  115. the error condition was the result of a client operation. By default, nothing
  116. related to the exception that triggered the view is passed to the template
  117. context, as the exception message might contain sensitive information like
  118. filesystem paths.
  119. ``bad_request`` views are also only used when :setting:`DEBUG` is ``False``.