models.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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 random
  7. import tempfile
  8. from pathlib import Path
  9. from django.core.files.storage import FileSystemStorage
  10. from django.db import models
  11. class CustomValidNameStorage(FileSystemStorage):
  12. def get_valid_name(self, name):
  13. # mark the name to show that this was called
  14. return name + '_valid'
  15. temp_storage_location = tempfile.mkdtemp()
  16. temp_storage = FileSystemStorage(location=temp_storage_location)
  17. def callable_storage():
  18. return temp_storage
  19. class CallableStorage(FileSystemStorage):
  20. def __call__(self):
  21. # no-op implementation.
  22. return self
  23. class Storage(models.Model):
  24. def custom_upload_to(self, filename):
  25. return 'foo'
  26. def random_upload_to(self, filename):
  27. # This returns a different result each time,
  28. # to make sure it only gets called once.
  29. return '%s/%s' % (random.randint(100, 999), filename)
  30. def pathlib_upload_to(self, filename):
  31. return Path('bar') / filename
  32. normal = models.FileField(storage=temp_storage, upload_to='tests')
  33. custom = models.FileField(storage=temp_storage, upload_to=custom_upload_to)
  34. pathlib_callable = models.FileField(storage=temp_storage, upload_to=pathlib_upload_to)
  35. pathlib_direct = models.FileField(storage=temp_storage, upload_to=Path('bar'))
  36. random = models.FileField(storage=temp_storage, upload_to=random_upload_to)
  37. custom_valid_name = models.FileField(
  38. storage=CustomValidNameStorage(location=temp_storage_location),
  39. upload_to=random_upload_to,
  40. )
  41. storage_callable = models.FileField(storage=callable_storage, upload_to='storage_callable')
  42. storage_callable_class = models.FileField(storage=CallableStorage, upload_to='storage_callable_class')
  43. default = models.FileField(storage=temp_storage, upload_to='tests', default='tests/default.txt')
  44. empty = models.FileField(storage=temp_storage)
  45. limited_length = models.FileField(storage=temp_storage, upload_to='tests', max_length=20)
  46. extended_length = models.FileField(storage=temp_storage, upload_to='tests', max_length=300)