默认情况下,django在本地存储文件,使用MEDIA_ROOT和MEDIA_URL设定。
Django也提供了写自定义的存储系统的方法。其允许你完全的自定义Django在哪里存储文件。
在模型中使用文件
当你使用FileField或ImageField时,Django提供一组API让你可以处理文件。
>>> car = Car.objects.get(name="57 Chevy")
>>> car.photo
<ImageFieldFile: chevy.jpg>
>>> car.photo.name
'cars/chevy.jpg'
>>> car.photo.path
'/media/cars/chevy.jpg'
>>> car.photo.url
'http://media.example.com/cars/chevy.jpg'
文件存储
Django会委托给一个文件存储系统来管理怎么和在哪里存储文件。
Django默认的文件存储由settings中的DEFAULT_FILE_STORAGE
。如果你不想明确的指定一个文件存储系统,其会被启用
存储对象(Storage objects)
>>> from django.core.files.base import ContentFile
>>> from django.core.files.storage import default_storage
>>> path = default_storage.save('/path/to/file', ContentFile('new content'))
>>> path
'/path/to/file'
>>> default_storage.size(path)
11
>>> default_storage.open(path).read()
'new content'
>>> default_storage.delete(path)
>>> default_storage.exists(path)
False
内置文件系统存储类
以下的代码会存储上传的文件于/media/photos
不调用你设置的MEDIA_ROOT
from django.core.files.storage import FileSystemStorage
from django.db import models
fs = FileSystemStorage(location='/media/photos')
class Car(models.Model):
...
photo = models.ImageField(storage=fs)