models.py 1.1 KB

123456789101112131415161718192021222324252627282930313233
  1. """
  2. Storing files according to a custom storage system
  3. ``FileField`` and its variations can take a ``storage`` argument to specify how
  4. and where files should be stored.
  5. """
  6. import os
  7. import random
  8. import tempfile
  9. from django.db import models
  10. from django.core.files.storage import FileSystemStorage
  11. temp_storage_location = tempfile.mkdtemp(dir=os.environ['DJANGO_TEST_TEMP_DIR'])
  12. temp_storage = FileSystemStorage(location=temp_storage_location)
  13. class Storage(models.Model):
  14. def custom_upload_to(self, filename):
  15. return 'foo'
  16. def random_upload_to(self, filename):
  17. # This returns a different result each time,
  18. # to make sure it only gets called once.
  19. return '%s/%s' % (random.randint(100, 999), filename)
  20. normal = models.FileField(storage=temp_storage, upload_to='tests')
  21. custom = models.FileField(storage=temp_storage, upload_to=custom_upload_to)
  22. random = models.FileField(storage=temp_storage, upload_to=random_upload_to)
  23. default = models.FileField(storage=temp_storage, upload_to='tests', default='tests/default.txt')
  24. empty = models.FileField(storage=temp_storage)