models.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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 django.core.files.storage import FileSystemStorage
  9. from django.db import models
  10. class CustomValidNameStorage(FileSystemStorage):
  11. def get_valid_name(self, name):
  12. # mark the name to show that this was called
  13. return name + '_valid'
  14. temp_storage_location = tempfile.mkdtemp()
  15. temp_storage = FileSystemStorage(location=temp_storage_location)
  16. class Storage(models.Model):
  17. def custom_upload_to(self, filename):
  18. return 'foo'
  19. def random_upload_to(self, filename):
  20. # This returns a different result each time,
  21. # to make sure it only gets called once.
  22. return '%s/%s' % (random.randint(100, 999), filename)
  23. normal = models.FileField(storage=temp_storage, upload_to='tests')
  24. custom = models.FileField(storage=temp_storage, upload_to=custom_upload_to)
  25. random = models.FileField(storage=temp_storage, upload_to=random_upload_to)
  26. custom_valid_name = models.FileField(
  27. storage=CustomValidNameStorage(location=temp_storage_location),
  28. upload_to=random_upload_to,
  29. )
  30. default = models.FileField(storage=temp_storage, upload_to='tests', default='tests/default.txt')
  31. empty = models.FileField(storage=temp_storage)
  32. limited_length = models.FileField(storage=temp_storage, upload_to='tests', max_length=20)
  33. extended_length = models.FileField(storage=temp_storage, upload_to='tests', max_length=300)