filefield.py 866 B

1234567891011121314151617181920212223242526272829
  1. from django.utils.deconstruct import deconstructible
  2. from django.utils import timezone
  3. from django.conf import settings
  4. import os
  5. @deconstructible
  6. class PathAndRename(object):
  7. def __init__(self, sub_path):
  8. self.path = sub_path
  9. full_path = "%s/%s" % (settings.MEDIA_ROOT, sub_path)
  10. if not os.path.exists(full_path):
  11. os.makedirs(full_path)
  12. def __call__(self, instance, filename):
  13. # set filename as random string
  14. ext = filename.split('.')[-1]
  15. t = timezone.now().strftime('%Y%m%d%H%M%S%f')
  16. # get filename
  17. if instance.pk:
  18. filename = '{}-{}.{}'.format(instance.pk, t, ext)
  19. else:
  20. # set filename as random string
  21. filename = '{}.{}'.format(t, ext)
  22. # return the whole path to the file
  23. return os.path.join(self.path , filename)