files.txt 6.28 KB
Newer Older
1 2 3 4
==============
Managing files
==============

5 6 7
This document describes Django's file access APIs for files such as those
uploaded by a user. The lower level APIs are general enough that you could use
them for other purposes. If you want to handle "static files" (JS, CSS, etc),
8
see :doc:`/howto/static-files/index`.
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

By default, Django stores files locally, using the :setting:`MEDIA_ROOT` and
:setting:`MEDIA_URL` settings. The examples below assume that you're using these
defaults.

However, Django provides ways to write custom `file storage systems`_ that
allow you to completely customize where and how Django stores files. The
second half of this document describes how these storage systems work.

.. _file storage systems: `File storage`_

Using files in models
=====================

When you use a :class:`~django.db.models.FileField` or
:class:`~django.db.models.ImageField`, Django provides a set of APIs you can use
to deal with that file.

27 28
Consider the following model, using an :class:`~django.db.models.ImageField` to
store a photo::
29

30 31
    from django.db import models

32 33 34 35 36 37 38 39
    class Car(models.Model):
        name = models.CharField(max_length=255)
        price = models.DecimalField(max_digits=5, decimal_places=2)
        photo = models.ImageField(upload_to='cars')

Any ``Car`` instance will have a ``photo`` attribute that you can use to get at
the details of the attached photo::

40
    >>> car = Car.objects.get(name="57 Chevy")
41 42 43
    >>> car.photo
    <ImageFieldFile: chevy.jpg>
    >>> car.photo.name
44
    'cars/chevy.jpg'
45
    >>> car.photo.path
46
    '/media/cars/chevy.jpg'
47
    >>> car.photo.url
48
    'http://media.example.com/cars/chevy.jpg'
49 50 51 52

This object -- ``car.photo`` in the example -- is a ``File`` object, which means
it has all the methods and attributes described below.

53 54 55 56 57
.. note::
    The file is saved as part of saving the model in the database, so the actual
    file name used on disk cannot be relied on until after the model has been
    saved.

58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
For example, you can change the file name by setting the file's
:attr:`~django.core.files.File.name` to a path relative to the file storage's
location (:setting:`MEDIA_ROOT` if you are using the default
:class:`~django.core.files.storage.FileSystemStorage`)::

    >>> import os
    >>> from django.conf import settings
    >>> initial_path = car.photo.path
    >>> car.photo.name = 'cars/chevy_ii.jpg'
    >>> new_path = settings.MEDIA_ROOT + car.photo.name
    >>> # Move the file on the filesystem
    >>> os.rename(initial_path, new_path)
    >>> car.save()
    >>> car.photo.path
    '/media/cars/chevy_ii.jpg'
    >>> car.photo.path == new_path
    True
75

76 77 78
The ``File`` object
===================

79 80 81
Internally, Django uses a :class:`django.core.files.File` instance any time it
needs to represent a file. This object is a thin wrapper around Python's
`built-in file object`_ with some Django-specific additions.
82

83
.. _built-in file object: https://docs.python.org/library/stdtypes.html#bltin-file-objects
84 85 86 87 88 89 90 91 92 93 94 95 96

Most of the time you'll simply use a ``File`` that Django's given you (i.e. a
file attached to a model as above, or perhaps an uploaded file).

If you need to construct a ``File`` yourself, the easiest way is to create one
using a Python built-in ``file`` object::

    >>> from django.core.files import File

    # Create a Python file object using open()
    >>> f = open('/tmp/hello.world', 'w')
    >>> myfile = File(f)

97 98
Now you can use any of the documented attributes and methods
of the :class:`~django.core.files.File` class.
99

100 101 102 103 104 105 106
Be aware that files created in this way are not automatically closed.
The following approach may be used to close files automatically::

    >>> from django.core.files import File

    # Create a Python file object using open() and the with statement
    >>> with open('/tmp/hello.world', 'w') as f:
107 108 109
    ...     myfile = File(f)
    ...     myfile.write('Hello World')
    ...
110 111 112 113 114 115
    >>> myfile.closed
    True
    >>> f.closed
    True

Closing files is especially important when accessing file fields in a loop
116
over a large number of objects. If files are not manually closed after
117
accessing them, the risk of running out of file descriptors may arise. This
Justin Bronn's avatar
Justin Bronn committed
118
may lead to the following error::
119 120 121 122

    IOError: [Errno 24] Too many open files


123 124 125 126 127 128 129 130 131 132 133 134
File storage
============

Behind the scenes, Django delegates decisions about how and where to store files
to a file storage system. This is the object that actually understands things
like file systems, opening and reading files, etc.

Django's default file storage is given by the :setting:`DEFAULT_FILE_STORAGE`
setting; if you don't explicitly provide a storage system, this is the one that
will be used.

See below for details of the built-in default file storage system, and see
135
:doc:`/howto/custom-file-storage` for information on writing your own file
136 137 138 139 140 141 142 143 144 145 146
storage system.

Storage objects
---------------

Though most of the time you'll want to use a ``File`` object (which delegates to
the proper storage for that file), you can use file storage systems directly.
You can create an instance of some custom file storage class, or -- often more
useful -- you can use the global default storage system::

    >>> from django.core.files.storage import default_storage
147
    >>> from django.core.files.base import ContentFile
148

149
    >>> path = default_storage.save('/path/to/file', ContentFile('new content'))
150
    >>> path
151
    '/path/to/file'
152

153
    >>> default_storage.size(path)
154 155 156 157 158 159 160 161
    11
    >>> default_storage.open(path).read()
    'new content'

    >>> default_storage.delete(path)
    >>> default_storage.exists(path)
    False

162
See :doc:`/ref/files/storage` for the file storage API.
163

164 165
.. _builtin-fs-storage:

166 167 168
The built-in filesystem storage class
-------------------------------------

169 170
Django ships with a :class:`django.core.files.storage.FileSystemStorage` class
which implements basic local filesystem file storage.
171 172

For example, the following code will store uploaded files under
173
``/media/photos`` regardless of what your :setting:`MEDIA_ROOT` setting is::
174 175 176 177 178 179 180 181 182 183

    from django.db import models
    from django.core.files.storage import FileSystemStorage

    fs = FileSystemStorage(location='/media/photos')

    class Car(models.Model):
        ...
        photo = models.ImageField(storage=fs)

184 185 186
:doc:`Custom storage systems </howto/custom-file-storage>` work the same way:
you can pass them in as the ``storage`` argument to a
:class:`~django.db.models.FileField`.