2013-10-27 20:26:51 +00:00
|
|
|
"""
|
2014-09-24 05:13:13 +00:00
|
|
|
Storing files according to a custom storage system
|
2013-10-27 20:26:51 +00:00
|
|
|
|
|
|
|
``FileField`` and its variations can take a ``storage`` argument to specify how
|
|
|
|
and where files should be stored.
|
|
|
|
"""
|
|
|
|
|
|
|
|
import random
|
|
|
|
import tempfile
|
|
|
|
|
|
|
|
from django.core.files.storage import FileSystemStorage
|
2015-01-28 12:35:27 +00:00
|
|
|
from django.db import models
|
2013-10-27 20:26:51 +00:00
|
|
|
|
|
|
|
|
2014-10-15 07:42:06 +00:00
|
|
|
class OldStyleFSStorage(FileSystemStorage):
|
|
|
|
"""
|
|
|
|
Storage backend without support for the ``max_length`` argument in
|
|
|
|
``get_available_name()`` and ``save()``; for backward-compatibility and
|
|
|
|
deprecation testing.
|
|
|
|
"""
|
|
|
|
def get_available_name(self, name):
|
|
|
|
return name
|
|
|
|
|
|
|
|
def save(self, name, content):
|
|
|
|
return super(OldStyleFSStorage, self).save(name, content)
|
|
|
|
|
|
|
|
|
2015-05-03 04:10:24 +00:00
|
|
|
class CustomValidNameStorage(FileSystemStorage):
|
|
|
|
def get_valid_name(self, name):
|
|
|
|
# mark the name to show that this was called
|
|
|
|
return name + '_valid'
|
|
|
|
|
|
|
|
|
2015-02-21 17:56:36 +00:00
|
|
|
temp_storage_location = tempfile.mkdtemp()
|
2013-10-27 20:26:51 +00:00
|
|
|
temp_storage = FileSystemStorage(location=temp_storage_location)
|
|
|
|
|
2013-11-03 04:36:09 +00:00
|
|
|
|
2013-10-27 20:26:51 +00: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)
|
2015-05-03 04:10:24 +00:00
|
|
|
custom_valid_name = models.FileField(
|
|
|
|
storage=CustomValidNameStorage(location=temp_storage_location),
|
|
|
|
upload_to=random_upload_to,
|
|
|
|
)
|
2013-10-27 20:26:51 +00:00
|
|
|
default = models.FileField(storage=temp_storage, upload_to='tests', default='tests/default.txt')
|
|
|
|
empty = models.FileField(storage=temp_storage)
|
2014-10-15 07:42:06 +00:00
|
|
|
limited_length = models.FileField(storage=temp_storage, upload_to='tests', max_length=20)
|
|
|
|
extended_length = models.FileField(storage=temp_storage, upload_to='tests', max_length=300)
|
|
|
|
old_style = models.FileField(
|
|
|
|
storage=OldStyleFSStorage(location=temp_storage_location),
|
|
|
|
upload_to='tests',
|
|
|
|
)
|