Created
March 26, 2010 22:50
-
-
Save vbmendes/345498 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os, uuid | |
from django.conf import settings | |
from django.db import models | |
from django.utils.encoding import smart_unicode, smart_str | |
class BannerFileField(models.FileField): | |
def pre_save(self, model_instance, add): | |
file = super(BannerFileField, self).pre_save(model_instance, add) | |
if not add: | |
old = model_instance.__class__.objects.get(pk=model_instance.pk) | |
try: | |
os.remove(getattr(old, self.name).path) | |
except OSError: | |
pass | |
f_ext = file.name.split('.')[-1] | |
while True: | |
name = uuid.uuid1() | |
f_name = name + u'.' + f_ext | |
f_new = smart_unicode(os.path.join(settings.MEDIA_ROOT, self.upload_to, f_name) | |
if not os.path.exists(f_new): | |
break | |
os.rename(file.path, f_new) | |
upload_to = self.upload_to | |
if not upload_to.endswith(u'/'): upload_to = upload_to + u'/' | |
file.name = self.upload_to + u'/' + f_name | |
return file |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment