FileField.storage
A storage object, which handles the storage and retrieval of your files. See Managing files for details on how to provide this object.
The default form widget for this field is a ClearableFileInput
.
Using a FileField
or an ImageField
(see below) in a model takes a few steps:
- In your settings file, you’ll need to define
MEDIA_ROOT
as the full path to a directory where you’d like Django to store uploaded files. (For performance, these files are not stored in the database.) DefineMEDIA_URL
as the base public URL of that directory. Make sure that this directory is writable by the Web server’s user account. - Add the
FileField
orImageField
to your model, defining theupload_to
option to specify a subdirectory ofMEDIA_ROOT
to use for uploaded files. - All that will be stored in your database is a path to the file (relative to
MEDIA_ROOT
). You’ll most likely want to use the convenienceurl
attribute provided by Django. For example, if yourImageField
is calledmug_shot
, you can get the absolute path to your image in a template with{{ object.mug_shot.url }}
.
For example, say your MEDIA_ROOT
is set to '/home/media'
, and upload_to
is set to 'photos/%Y/%m/%d'
. The '%Y/%m/%d'
part of upload_to
is strftime()
formatting; '%Y'
is the four-digit year, '%m'
is the two-digit month and '%d'
is the two-digit day. If you upload a file on Jan. 15, 2007, it will be saved in the directory /home/media/photos/2007/01/15
.
If you wanted to retrieve the uploaded file’s on-disk filename, or the file’s size, you could use the name
and size
attributes respectively; for more information on the available attributes and methods, see the File
class reference and the Managing files topic guide.
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.
The uploaded file’s relative URL can be obtained using the url
attribute. Internally, this calls the url()
method of the underlying Storage
class.
Note that whenever you deal with uploaded files, you should pay close attention to where you’re uploading them and what type of files they are, to avoid security holes. Validate all uploaded files so that you’re sure the files are what you think they are. For example, if you blindly let somebody upload files, without validation, to a directory that’s within your Web server’s document root, then somebody could upload a CGI or PHP script and execute that script by visiting its URL on your site. Don’t allow that.
Also note that even an uploaded HTML file, since it can be executed by the browser (though not by the server), can pose security threats that are equivalent to XSS or CSRF attacks.
FileField
instances are created in your database as varchar
columns with a default max length of 100 characters. As with other fields, you can change the maximum length using the max_length
argument.
Please login to continue.