Created
April 5, 2010 08:11
-
-
Save avostryakov/356141 to your computer and use it in GitHub Desktop.
This file contains 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 | |
from django.core.files.storage import FileSystemStorage | |
from django.db.models import signals | |
class MyFileSystemStorage(FileSystemStorage): | |
def rename(self, src, dest): | |
return os.rename(self.path(src), self.path(dest)) | |
class MyFileField(models.FileField): | |
def __init__(self, *args, **kwargs): | |
super(MyFileField, self).__init__(*args, **kwargs) | |
self.storage = MyFileSystemStorage() | |
def pre_save(self, model_instance, add): | |
file = getattr(model_instance, self.attname) | |
filename = self.upload_to(model_instance, file.name) | |
if file and file._committed: | |
if file.name != filename: | |
file.storage.rename(file.name, filename) | |
file.name = filename | |
return file | |
def save_file(self, instance, sender, **kwargs): | |
file = getattr(instance, self.attname) | |
if file and not file._committed: | |
filename = self.upload_to(instance, file.name) | |
file.save(filename, file, save=file.name!=filename) | |
return file | |
def contribute_to_class(self, cls, name): | |
super(MyFileField, self).contribute_to_class(cls, name) | |
signals.post_save.connect(self.save_file, sender=cls) | |
class MyModel(models.Model): | |
title = models.CharField(max_length=200) | |
file = MyFileField(upload_to=lambda instance, filename: 'files/%s_%s' % (instance.pk, instance.title)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment