views.txt 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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.views.static import serve
  23. # ... the rest of your URLconf goes here ...
  24. if settings.DEBUG:
  25. urlpatterns += [
  26. url(r'^media/(?P<path>.*)$', serve, {
  27. 'document_root': settings.MEDIA_ROOT,
  28. }),
  29. ]
  30. Note, the snippet assumes your :setting:`MEDIA_URL` has a value of
  31. ``'/media/'``. This will call the :func:`~django.views.static.serve` view,
  32. passing in the path from the URLconf and the (required) ``document_root``
  33. parameter.
  34. Since it can become a bit cumbersome to define this URL pattern, Django
  35. ships with a small URL helper function :func:`~django.conf.urls.static.static`
  36. that takes as parameters the prefix such as :setting:`MEDIA_URL` and a dotted
  37. path to a view, such as ``'django.views.static.serve'``. Any other function
  38. parameter will be transparently passed to the view.