files.txt 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. ==============
  2. Managing files
  3. ==============
  4. This document describes Django's file access APIs for files such as those
  5. uploaded by a user. The lower level APIs are general enough that you could use
  6. them for other purposes. If you want to handle "static files" (JS, CSS, etc),
  7. see :doc:`/howto/static-files/index`.
  8. By default, Django stores files locally, using the :setting:`MEDIA_ROOT` and
  9. :setting:`MEDIA_URL` settings. The examples below assume that you're using these
  10. defaults.
  11. However, Django provides ways to write custom `file storage systems`_ that
  12. allow you to completely customize where and how Django stores files. The
  13. second half of this document describes how these storage systems work.
  14. .. _file storage systems: `File storage`_
  15. Using files in models
  16. =====================
  17. When you use a :class:`~django.db.models.FileField` or
  18. :class:`~django.db.models.ImageField`, Django provides a set of APIs you can use
  19. to deal with that file.
  20. Consider the following model, using an :class:`~django.db.models.ImageField` to
  21. store a photo::
  22. class Car(models.Model):
  23. name = models.CharField(max_length=255)
  24. price = models.DecimalField(max_digits=5, decimal_places=2)
  25. photo = models.ImageField(upload_to='cars')
  26. Any ``Car`` instance will have a ``photo`` attribute that you can use to get at
  27. the details of the attached photo::
  28. >>> car = Car.objects.get(name="57 Chevy")
  29. >>> car.photo
  30. <ImageFieldFile: chevy.jpg>
  31. >>> car.photo.name
  32. u'cars/chevy.jpg'
  33. >>> car.photo.path
  34. u'/media/cars/chevy.jpg'
  35. >>> car.photo.url
  36. u'http://media.example.com/cars/chevy.jpg'
  37. This object -- ``car.photo`` in the example -- is a ``File`` object, which means
  38. it has all the methods and attributes described below.
  39. .. note::
  40. The file is saved as part of saving the model in the database, so the actual
  41. file name used on disk cannot be relied on until after the model has been
  42. saved.
  43. The ``File`` object
  44. ===================
  45. Internally, Django uses a :class:`django.core.files.File` instance any time it
  46. needs to represent a file. This object is a thin wrapper around Python's
  47. `built-in file object`_ with some Django-specific additions.
  48. .. _built-in file object: http://docs.python.org/library/stdtypes.html#bltin-file-objects
  49. Most of the time you'll simply use a ``File`` that Django's given you (i.e. a
  50. file attached to a model as above, or perhaps an uploaded file).
  51. If you need to construct a ``File`` yourself, the easiest way is to create one
  52. using a Python built-in ``file`` object::
  53. >>> from django.core.files import File
  54. # Create a Python file object using open()
  55. >>> f = open('/tmp/hello.world', 'w')
  56. >>> myfile = File(f)
  57. Now you can use any of the documented attributes and methods
  58. of the :class:`~django.core.files.File` class.
  59. Be aware that files created in this way are not automatically closed.
  60. The following approach may be used to close files automatically::
  61. >>> from django.core.files import File
  62. # Create a Python file object using open() and the with statement
  63. >>> with open('/tmp/hello.world', 'w') as f:
  64. >>> myfile = File(f)
  65. >>> for line in myfile:
  66. >>> print line
  67. >>> myfile.closed
  68. True
  69. >>> f.closed
  70. True
  71. Closing files is especially important when accessing file fields in a loop
  72. over a large number of objects:: If files are not manually closed after
  73. accessing them, the risk of running out of file descriptors may arise. This
  74. may lead to the following error::
  75. IOError: [Errno 24] Too many open files
  76. File storage
  77. ============
  78. Behind the scenes, Django delegates decisions about how and where to store files
  79. to a file storage system. This is the object that actually understands things
  80. like file systems, opening and reading files, etc.
  81. Django's default file storage is given by the :setting:`DEFAULT_FILE_STORAGE`
  82. setting; if you don't explicitly provide a storage system, this is the one that
  83. will be used.
  84. See below for details of the built-in default file storage system, and see
  85. :doc:`/howto/custom-file-storage` for information on writing your own file
  86. storage system.
  87. Storage objects
  88. ---------------
  89. Though most of the time you'll want to use a ``File`` object (which delegates to
  90. the proper storage for that file), you can use file storage systems directly.
  91. You can create an instance of some custom file storage class, or -- often more
  92. useful -- you can use the global default storage system::
  93. >>> from django.core.files.storage import default_storage
  94. >>> from django.core.files.base import ContentFile
  95. >>> path = default_storage.save('/path/to/file', ContentFile('new content'))
  96. >>> path
  97. u'/path/to/file'
  98. >>> default_storage.size(path)
  99. 11
  100. >>> default_storage.open(path).read()
  101. 'new content'
  102. >>> default_storage.delete(path)
  103. >>> default_storage.exists(path)
  104. False
  105. See :doc:`/ref/files/storage` for the file storage API.
  106. .. _builtin-fs-storage:
  107. The built-in filesystem storage class
  108. -------------------------------------
  109. Django ships with a built-in ``FileSystemStorage`` class (defined in
  110. ``django.core.files.storage``) which implements basic local filesystem file
  111. storage. Its initializer takes two arguments:
  112. ====================== ===================================================
  113. Argument Description
  114. ====================== ===================================================
  115. ``location`` Optional. Absolute path to the directory that will
  116. hold the files. If omitted, it will be set to the
  117. value of your :setting:`MEDIA_ROOT` setting.
  118. ``base_url`` Optional. URL that serves the files stored at this
  119. location. If omitted, it will default to the value
  120. of your :setting:`MEDIA_URL` setting.
  121. ====================== ===================================================
  122. For example, the following code will store uploaded files under
  123. ``/media/photos`` regardless of what your :setting:`MEDIA_ROOT` setting is::
  124. from django.db import models
  125. from django.core.files.storage import FileSystemStorage
  126. fs = FileSystemStorage(location='/media/photos')
  127. class Car(models.Model):
  128. ...
  129. photo = models.ImageField(storage=fs)
  130. :doc:`Custom storage systems </howto/custom-file-storage>` work the same way:
  131. you can pass them in as the ``storage`` argument to a
  132. :class:`~django.db.models.FileField`.