Skip to content

Instantly share code, notes, and snippets.

@githubutilities
Last active November 26, 2015 05:19
Show Gist options
  • Select an option

  • Save githubutilities/aff0ddd40cc6f467f623 to your computer and use it in GitHub Desktop.

Select an option

Save githubutilities/aff0ddd40cc6f467f623 to your computer and use it in GitHub Desktop.
Managing ImageField

Managing ImageField With Triggers

Models

#coding=utf8
from django.db import models


class AdsPicture(models.Model):
    name = models.CharField(max_length=100, default="")
    image = models.ImageField(upload_to='ads', default="")
    rank = models.IntegerField(unique=True, default=1)

    @property
    def img(self):
        return self.image

    @img.setter
    def img(self, value):
        self.image.delete(False)
        self.image = value

Trigger only works when imported

# Trigger for AdsPicture Model
# Receive the pre_delete signal and delete the file associated with the model instance.
from django.db.models.signals import pre_delete
from django.dispatch.dispatcher import receiver


@receiver(pre_delete, sender=AdsPicture)
def ads_picture_pre_delete(sender, instance, **kwargs):
    instance.image.delete(False)

Settings.py

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

MEDIA_URL = '/media/'

Urls.py

if not settings.DEPLOYED:
    urlpatterns += url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
                'document_root': settings.MEDIA_ROOT,
            }),

Calculating MD5 Hash

import hashlib


def get_hash(file):
    md5 = hashlib.md5()
    # use `UploadedFile.chunks(chunk_size=None)` to avoid reading whole file into memory
    for data in file.chunks():
        md5.update(data)
    file.seek(0)
    checksum = md5.hexdigest()
    return checksum
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment