models.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. class OldStyleFSStorage(FileSystemStorage):
  12. """
  13. Storage backend without support for the ``max_length`` argument in
  14. ``get_available_name()`` and ``save()``; for backward-compatibility and
  15. deprecation testing.
  16. """
  17. def get_available_name(self, name):
  18. return name
  19. def save(self, name, content):
  20. return super(OldStyleFSStorage, self).save(name, content)
  21. temp_storage_location = tempfile.mkdtemp(dir=os.environ['DJANGO_TEST_TEMP_DIR'])
  22. temp_storage = FileSystemStorage(location=temp_storage_location)
  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. normal = models.FileField(storage=temp_storage, upload_to='tests')
  31. custom = models.FileField(storage=temp_storage, upload_to=custom_upload_to)
  32. random = models.FileField(storage=temp_storage, upload_to=random_upload_to)
  33. default = models.FileField(storage=temp_storage, upload_to='tests', default='tests/default.txt')
  34. empty = models.FileField(storage=temp_storage)
  35. limited_length = models.FileField(storage=temp_storage, upload_to='tests', max_length=20)
  36. extended_length = models.FileField(storage=temp_storage, upload_to='tests', max_length=300)
  37. old_style = models.FileField(
  38. storage=OldStyleFSStorage(location=temp_storage_location),
  39. upload_to='tests',
  40. )