models.py 1.1 KB

12345678910111213141516171819202122232425262728293031
  1. """
  2. 42. 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 random
  7. import tempfile
  8. from django.db import models
  9. from django.core.files.storage import FileSystemStorage
  10. temp_storage_location = tempfile.mkdtemp()
  11. temp_storage = FileSystemStorage(location=temp_storage_location)
  12. class Storage(models.Model):
  13. def custom_upload_to(self, filename):
  14. return 'foo'
  15. def random_upload_to(self, filename):
  16. # This returns a different result each time,
  17. # to make sure it only gets called once.
  18. return '%s/%s' % (random.randint(100, 999), filename)
  19. normal = models.FileField(storage=temp_storage, upload_to='tests')
  20. custom = models.FileField(storage=temp_storage, upload_to=custom_upload_to)
  21. random = models.FileField(storage=temp_storage, upload_to=random_upload_to)
  22. default = models.FileField(storage=temp_storage, upload_to='tests', default='tests/default.txt')
  23. empty = models.FileField(storage=temp_storage)