/tests/modeltests/files/models.py

https://code.google.com/p/mango-py/ · Python · 34 lines · 17 code · 8 blank · 9 comment · 0 complexity · 1f115d71467bf367b818e1c66a7d9656 MD5 · raw file

  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.base import ContentFile
  10. from django.core.files.storage import FileSystemStorage
  11. temp_storage_location = tempfile.mkdtemp()
  12. temp_storage = FileSystemStorage(location=temp_storage_location)
  13. # Write out a file to be used as default content
  14. temp_storage.save('tests/default.txt', ContentFile('default content'))
  15. class Storage(models.Model):
  16. def custom_upload_to(self, filename):
  17. return 'foo'
  18. def random_upload_to(self, filename):
  19. # This returns a different result each time,
  20. # to make sure it only gets called once.
  21. return '%s/%s' % (random.randint(100, 999), filename)
  22. normal = models.FileField(storage=temp_storage, upload_to='tests')
  23. custom = models.FileField(storage=temp_storage, upload_to=custom_upload_to)
  24. random = models.FileField(storage=temp_storage, upload_to=random_upload_to)
  25. default = models.FileField(storage=temp_storage, upload_to='tests', default='tests/default.txt')