##// END OF EJS Templates
Deduplicated upload_to method for images and file attachments
Deduplicated upload_to method for images and file attachments

File last commit:

r1368:3a697667 default
r1368:3a697667 default
Show More
__init__.py
43 lines | 1.2 KiB | text/x-python | PythonLexer
from django.db import models
from boards import utils
from boards.models.attachment.viewers import get_viewers, AbstractViewer
from boards.utils import get_upload_filename
FILES_DIRECTORY = 'files/'
FILE_EXTENSION_DELIMITER = '.'
class AttachmentManager(models.Manager):
def create_with_hash(self, file):
file_hash = utils.get_file_hash(file)
existing = self.filter(hash=file_hash)
if len(existing) > 0:
attachment = existing[0]
else:
file_type = file.name.split(FILE_EXTENSION_DELIMITER)[-1].lower()
attachment = Attachment.objects.create(
file=file, mimetype=file_type, hash=file_hash)
return attachment
class Attachment(models.Model):
objects = AttachmentManager()
file = models.FileField(upload_to=get_upload_filename)
mimetype = models.CharField(max_length=50)
hash = models.CharField(max_length=36)
def get_view(self):
file_viewer = None
for viewer in get_viewers():
if viewer.supports(self.mimetype):
file_viewer = viewer
break
if file_viewer is None:
file_viewer = AbstractViewer
return file_viewer(self.file, self.mimetype).get_view()