Django documentation

This document is for Django's SVN release, which can be significantly different from previous releases. Get old docs here: Django 1.0

The File object

class File(file_object)

File attributes and methods

Django’s File has the following attributes and methods:
The name of file including the relative path from MEDIA_ROOT.

The absolute path to the file’s location on a local filesystem.

Custom file storage systems may not store files locally; files stored on these systems will have a path of None.


The URL where the file can be retrieved. This is often useful in templates; for example, a bit of a template for displaying a Car (see above) might look like:

<img src='{{ }}' alt='{{ }}' />
The size of the file in bytes.

Open or reopen the file (which by definition also does The mode argument allows the same values as Python's standard open().

When reopening a file, mode will override whatever mode the file was originally opened with; None means to reopen with the original mode.
Read content from the file. The optional size is the number of bytes to read; if not specified, the file will be read to the end.
Iterate over the file yielding one line at a time.

Iterate over the file yielding "chunks" of a given size. chunk_size defaults to 64 KB.

This is especially useful with very large files since it allows them to be streamed off disk and avoids storing the whole file in memory.

Returns True if the file is large enough to require multiple chunks to access all of its content give some chunk_size.
Writes the specified content string to the file. Depending on the storage system behind the scenes, this content might not be fully committed until close() is called on the file.
Close the file.

Additional ImageField attributes

Width of the image.
Height of the image.

Additional methods on files attached to objects

Any File that's associated with an object (as with, above) will also have a couple of extra methods:, content, save=True)

Saves a new file with the file name and contents provided. This will not replace the existing file, but will create a new file and update the object to point to it. If save is True, the model's save() method will be called once the file is saved. That is, these two lines:

>>>'myphoto.jpg', contents, save=False)

are the same as this one line:

>>>'myphoto.jpg', contents, save=True)

Note that the content argument must be an instance of File or of a subclass of File.

Remove the file from the model instance and delete the underlying file. The save argument works as above.


Having trouble? We'd like to help!