files.txt 6.1 KB

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