2008-08-09 04:59:02 +08:00
|
|
|
"""
|
|
|
|
42. Storing files according to a custom storage system
|
|
|
|
|
2008-08-12 22:15:38 +08:00
|
|
|
``FileField`` and its variations can take a ``storage`` argument to specify how
|
|
|
|
and where files should be stored.
|
2008-08-09 04:59:02 +08:00
|
|
|
"""
|
|
|
|
|
2009-05-08 23:08:09 +08:00
|
|
|
import random
|
2008-08-09 04:59:02 +08:00
|
|
|
import tempfile
|
2010-09-13 04:03:55 +08:00
|
|
|
|
2008-08-09 04:59:02 +08:00
|
|
|
from django.db import models
|
|
|
|
from django.core.files.base import ContentFile
|
|
|
|
from django.core.files.storage import FileSystemStorage
|
|
|
|
|
2010-09-13 04:03:55 +08:00
|
|
|
|
2008-10-11 04:09:51 +08:00
|
|
|
temp_storage_location = tempfile.mkdtemp()
|
|
|
|
temp_storage = FileSystemStorage(location=temp_storage_location)
|
2008-08-09 04:59:02 +08:00
|
|
|
|
|
|
|
class Storage(models.Model):
|
|
|
|
def custom_upload_to(self, filename):
|
|
|
|
return 'foo'
|
|
|
|
|
|
|
|
def random_upload_to(self, filename):
|
|
|
|
# This returns a different result each time,
|
|
|
|
# to make sure it only gets called once.
|
|
|
|
return '%s/%s' % (random.randint(100, 999), filename)
|
|
|
|
|
|
|
|
normal = models.FileField(storage=temp_storage, upload_to='tests')
|
|
|
|
custom = models.FileField(storage=temp_storage, upload_to=custom_upload_to)
|
|
|
|
random = models.FileField(storage=temp_storage, upload_to=random_upload_to)
|
|
|
|
default = models.FileField(storage=temp_storage, upload_to='tests', default='tests/default.txt')
|