Created
January 9, 2012 19:20
-
-
Save fabiomontefuscolo/1584462 to your computer and use it in GitHub Desktop.
Let the Django FileField overwrite files with the same name
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
# -*- coding: utf-8 -*- | |
from django.conf import settings | |
from django.core.files.storage import FileSystemStorage | |
from django.db import models | |
class OverwriteStorage(FileSystemStorage): | |
''' | |
Muda o comportamento padrão do Django e o faz sobrescrever arquivos de | |
mesmo nome que foram carregados pelo usuário ao invés de renomeá-los. | |
''' | |
def get_available_name(self, name): | |
if self.exists(name): | |
os.remove(os.path.join(settings.MEDIA_ROOT, name)) | |
return name | |
class Media(models.Model): | |
name = models.CharField(u"Nome", max_length=128)) | |
media = models.FileField(u"Arquivo", upload_to=settings.MEDIA_DIR, storage=OverwriteStorage()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks! Helped me fix my problem quickly.
Here’s a sidenote: The original
get_available_name
method e.g. does a check for suspicious file operations and max_length. To benefit from the original method, call super():storage.py
… and in settings.py: