Better upload helper and admin integration

This commit is contained in:
Felipe Martín 2016-03-21 22:49:39 +01:00
parent acb4e22739
commit 8b1c2cb3c6
3 changed files with 17 additions and 3 deletions

View File

@ -87,6 +87,11 @@ admin.site.register(Tag, TagAdmin)
# ATTACHMENT
#
class AttachmentAdmin(VersionAdmin):
pass
list_display = ('filename', 'sha1', )
fields = ('file', )
def save_model(self, request, obj, form, change):
handler = form.cleaned_data.get('file')
Attachment.upload(handler, handler.name)
admin.site.register(Attachment, AttachmentAdmin)

View File

@ -125,7 +125,7 @@ class Attachment(models.Model):
return 'attachment/{}/{}/{}/'.format(p1, p2, self.sha1)
@staticmethod
def upload_file(handler, filename=None):
def upload(handler, filename=None):
"""
Given a certain file handler returns an `Image` objects
handler can be:

View File

@ -1,8 +1,17 @@
# -*- coding: utf-8 -*-
import hashlib
import uuid
from django.core.files.uploadedfile import InMemoryUploadedFile
def sha1_checksum(handler):
f = open(handler.file.name, 'rb')
if isinstance(handler, InMemoryUploadedFile):
temp_name = '/tmp/_{}'.format(uuid.uuid4())
f = open(temp_name, 'wb+')
f.write(handler.read())
else:
f = open(handler.name, 'rb')
checksum = hashlib.sha1(f.read())
return checksum.hexdigest()