Fix typo in docs/files.txt
[django.git] / docs / files.txt
blob674fb01e87984c03525d30986e003bd64a5f9d75
1 ==============
2 Managing files
3 ==============
5 **New in Django development version**
7 This document describes Django's file access APIs.
9 By default, Django stores files locally, using the ``MEDIA_ROOT`` and
10 ``MEDIA_URL`` settings_. The examples below assume that you're using
11 these defaults.
13 However, Django provides ways to write custom `file storage systems`_ that
14 allow you to completely customize where and how Django stores files. The
15 second half of this document describes how these storage systems work.
17 .. _file storage systems: `File storage`_
18 .. _settings: ../settings/
20 Using files in models
21 =====================
23 When you use a `FileField`_ or `ImageField`_, Django provides a set of APIs you can use to deal with that file.
25 .. _filefield: ../model-api/#filefield
26 .. _imagefield: ../model-api/#imagefield
28 Consider the following model, using a ``FileField`` to store a photo::
30     class Car(models.Model):
31         name = models.CharField(max_length=255)
32         price = models.DecimalField(max_digits=5, decimal_places=2)
33         photo = models.ImageField(upload_to='cars')
35 Any ``Car`` instance will have a ``photo`` attribute that you can use to get at
36 the details of the attached photo::
38     >>> car = Car.object.get(name="57 Chevy")
39     >>> car.photo
40     <ImageFieldFile: chevy.jpg>
41     >>> car.photo.name
42     u'chevy.jpg'
43     >>> car.photo.path
44     u'/media/cars/chevy.jpg'
45     >>> car.photo.url
46     u'http://media.example.com/cars/chevy.jpg'
47     
48 This object -- ``car.photo`` in the example -- is a ``File`` object, which means
49 it has all the methods and attributes described below.
51 The ``File`` object
52 ===================
54 Internally, Django uses a ``django.core.files.File`` any time it needs to
55 represent a file. This object is a thin wrapper around Python's `built-in file
56 object`_ with some Django-specific additions.
58 .. _built-in file object: http://docs.python.org/lib/bltin-file-objects.html
60 Creating ``File`` instances
61 ---------------------------
63 Most of the time you'll simply use a ``File`` that Django's given you (i.e. a
64 file attached to an model as above, or perhaps an `uploaded file`_).
66 .. _uploaded file: ../uploading_files/
68 If you need to construct a ``File`` yourself, the easiest way is to create one
69 using a Python built-in ``file`` object::
71     >>> from django.core.files import File
73     # Create a Python file object using open()
74     >>> f = open('/tmp/hello.world', 'w')
75     >>> myfile = File(f)
76     
77 Now you can use any of the ``File`` attributes and methods defined below.
78     
79 ``File`` attributes and methods
80 -------------------------------
82 Django's ``File`` has the following attributes and methods:
84 ``File.path``
85 ~~~~~~~~~~~~~
87 The absolute path to the file's location on a local filesystem. 
89 Custom `file storage systems`_ may not store files locally; files stored on
90 these systems will have a ``path`` of ``None``.
92 ``File.url``
93 ~~~~~~~~~~~~
95 The URL where the file can be retrieved. This is often useful in templates_; for
96 example, a bit of a template for displaying a ``Car`` (see above) might look
97 like::
99     <img src='{{ car.photo.url }}' alt='{{ car.name }}' />
101 .. _templates: ../templates/
103 ``File.size``
104 ~~~~~~~~~~~~~
106 The size of the file in bytes.
108 ``File.open(mode=None)``
109 ~~~~~~~~~~~~~~~~~~~~~~~~
111 Open or reopen the file (which by definition also does ``File.seek(0)``). The
112 ``mode`` argument allows the same values as Python's standard ``open()``.
114 When reopening a file, ``mode`` will override whatever mode the file was
115 originally opened with; ``None`` means to reopen with the original mode.
117 ``File.read(num_bytes=None)``
118 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
120 Read content from the file. The optional ``size`` is the number of bytes to
121 read; if not specified, the file will be read to the end.
123 ``File.__iter__()``
124 ~~~~~~~~~~~~~~~~~~~
126 Iterate over the file yielding one line at a time.
128 ``File.chunks(chunk_size=None)``
129 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
131 Iterate over the file yielding "chunks" of a given size. ``chunk_size`` defaults
132 to 64 KB.
134 This is especially useful with very large files since it allows them to be
135 streamed off disk and avoids storing the whole file in memory.
137 ``File.multiple_chunks(chunk_size=None)``
138 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
140 Returns ``True`` if the file is large enough to require multiple chunks to
141 access all of its content give some ``chunk_size``.
143 ``File.write(content)``
144 ~~~~~~~~~~~~~~~~~~~~~~~
146 Writes the specified content string to the file. Depending on the storage system
147 behind the scenes, this content might not be fully committed until ``close()``
148 is called on the file.
150 ``File.close()``
151 ~~~~~~~~~~~~~~~~
153 Close the file.
155 .. TODO: document the rest of the File methods.
157 Additional ``ImageField`` attributes
158 ------------------------------------
160 ``File.width`` and ``File.height``
161 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
163 These attributes provide the dimensions of the image. 
165 Additional methods on files attached to objects
166 -----------------------------------------------
168 Any ``File`` that's associated with an object (as with ``Car.photo``, above)
169 will also have a couple of extra methods:
171 ``File.save(name, content, save=True)``
172 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
174 Saves a new file with the file name and contents provided. This will not replace
175 the existing file, but will create a new file and update the object to point to
176 it. If ``save`` is ``True``, the model's ``save()`` method will be called once
177 the file is saved. That is, these two lines::
179     >>> car.photo.save('myphoto.jpg', contents, save=False)
180     >>> car.save()
182 are the same as this one line::
184     >>> car.photo.save('myphoto.jpg', contents, save=True)
186 ``File.delete(save=True)``
187 ~~~~~~~~~~~~~~~~~~~~~~~~~~
189 Remove the file from the model instance and delete the underlying file. The
190 ``save`` argument works as above.
192 File storage
193 ============
195 Behind the scenes, Django delegates decisions about how and where to store files
196 to a file storage system. This is the object that actually understands things
197 like file systems, opening and reading files, etc.
199 Django's default file storage is given by the `DEFAULT_FILE_STORAGE setting`_;
200 if you don't explicitly provide a storage system, this is the one that will be
201 used. 
203 .. _default_file_storage setting: ../settings/#default-file-storage
205 The built-in filesystem storage class
206 -------------------------------------
208 Django ships with a built-in ``FileSystemStorage`` class (defined in
209 ``django.core.files.storage``) which implements basic local filesystem file
210 storage. Its initializer takes two arguments:
212 ======================  ===================================================
213 Argument                Description
214 ======================  ===================================================
215 ``location``            Optional. Absolute path to the directory that will
216                         hold the files. If omitted, it will be set to the
217                         value of your ``MEDIA_ROOT`` setting.
218 ``base_url``            Optional. URL that serves the files stored at this
219                         location. If omitted, it will default to the value
220                         of your ``MEDIA_URL`` setting.
221 ======================  ===================================================
223 For example, the following code will store uploaded files under
224 ``/media/photos`` regardless of what your ``MEDIA_ROOT`` setting is::
226     from django.db import models
227     from django.core.files.storage import FileSystemStorage
229     fs = FileSystemStorage(location='/media/photos')
231     class Car(models.Model):
232         ...
233         photo = models.ImageField(storage=fs)
235 `Custom storage systems`_ work the same way: you can pass them in as the
236 ``storage`` argument to a ``FileField``.
238 .. _custom storage systems: `writing a custom storage system`_
240 Storage objects
241 ---------------
243 Though most of the time you'll want to use a ``File`` object (which delegates to
244 the proper storage for that file), you can use file storage systems directly.
245 You can create an instance of some custom file storage class, or -- often more
246 useful -- you can use the global default storage system::
248     >>> from django.core.files.storage import default_storage
250     >>> path = default_storage.save('/path/to/file', 'new content')
251     >>> path
252     u'/path/to/file'
254     >>> default_storage.filesize(path)
255     11
256     >>> default_storage.open(path).read()
257     'new content'
259     >>> default_storage.delete(path)
260     >>> default_storage.exists(path)
261     False
263 Storage objects define the following methods:
265 ``Storage.exists(name)``
266 ~~~~~~~~~~~~~~~~~~~~~~~~
268 ``True`` if a file exists given some ``name``.
270 ``Storage.path(name)``
271 ~~~~~~~~~~~~~~~~~~~~~~
273 The local filesystem path where the file can be opened using Python's standard
274 ``open()``. For storage systems that aren't accessible from the local
275 filesystem, this will raise ``NotImplementedError`` instead.
277 ``Storage.size(name)``
278 ~~~~~~~~~~~~~~~~~~~~~~
280 Returns the total size, in bytes, of the file referenced by ``name``.
282 ``Storage.url(name)``
283 ~~~~~~~~~~~~~~~~~~~~~
285 Returns the URL where the contents of the file referenced by ``name`` can be
286 accessed.
288 ``Storage.open(name, mode='rb')``
289 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
291 Opens the file given by ``name``. Note that although the returned file is
292 guaranteed to be a ``File`` object, it might actually be some subclass. In the
293 case of remote file storage this means that reading/writing could be quite slow,
294 so be warned.
296 ``Storage.save(name, content)``
297 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
299 Saves a new file using the storage system, preferably with the name specified.
300 If there already exists a file with this name ``name``, the storage system may
301 modify the filename as necessary to get a unique name. The actual name of the
302 stored file will be returned.
304 ``Storage.delete(name)``
305 ~~~~~~~~~~~~~~~~~~~~~~~~
307 Deletes the file referenced by ``name``. This method won't raise an exception if
308 the file doesn't exist.
310 Writing a custom storage system
311 ===============================
313 If you need to provide custom file storage -- a common example is storing files
314 on some remote system -- you can do so by defining a custom storage class.
315 You'll need to follow these steps:
317 #. Your custom storage system must be a subclass of 
318    ``django.core.files.storage.Storage``::
320         from django.core.files.storage import Storage
321     
322         class MyStorage(Storage):
323             ...
324         
325 #. Django must be able to instantiate your storage system without any arguments. 
326    This means that any settings should be taken from ``django.conf.settings``::
327    
328         from django.conf import settings
329         from django.core.files.storage import Storage
331         class MyStorage(Storage):
332             def __init__(self, option=None):
333                 if not option:
334                     option = settings.CUSTOM_STORAGE_OPTIONS
335                 ...
337 #. Your storage class must implement the ``_open()`` and ``_save()`` methods,
338    along with any other methods appropriate to your storage class. See below for
339    more on these methods. 
340    
341    In addition, if your class provides local file storage, it must override
342    the ``path()`` method.
343    
344 Custom storage system methods
345 -----------------------------
347 Your custom storage system may override any of the storage methods explained
348 above in `storage objects`_. However, it's usually better to use the hooks
349 specifically designed for custom storage objects. These are:
351 ``_open(name, mode='rb')``
352 ~~~~~~~~~~~~~~~~~~~~~~~~~~
354 **Required**.
356 Called by ``Storage.open()``, this is the actual mechanism the storage class
357 uses to open the file. This must return a ``File`` object, though in most cases,
358 you'll want to return some subclass here that implements logic specific to the
359 backend storage system.
361 ``_save(name, content)``
362 ~~~~~~~~~~~~~~~~~~~~~~~~
364 Called by ``Storage.save()``. The ``name`` will already have gone through
365 ``get_valid_name()`` and ``get_available_name()``, and the ``content`` will be a
366 ``File`` object itself. No return value is expected.
368 ``get_valid_name(name)``
369 ------------------------
371 Returns a filename suitable for use with the underlying storage system. The
372 ``name`` argument passed to this method is the original filename sent to the
373 server, after having any path information removed. Override this to customize
374 how non-standard characters are converted to safe filenames.
376 The code provided on ``Storage`` retains only alpha-numeric characters, periods
377 and underscores from the original filename, removing everything else.
379 ``get_available_name(name)``
380 ----------------------------
382 Returns a filename that is available in the storage mechanism, possibly taking
383 the provided filename into account. The ``name`` argument passed to this method
384 will have already cleaned to a filename valid for the storage system, according
385 to the ``get_valid_name()`` method described above.
387 The code provided on ``Storage`` simply appends underscores to the filename
388 until it finds one that's available in the destination directory.