Source

mediatr / signals.py

import mimetypes
import os.path
from django.template.defaultfilters import slugify

from helpers import make_hash


# init mime types dict
mimetypes.init()

class WrongObjectException(Exception):
    "Passed objects did not match requirements"
    pass

def add_mime_type(instance, **kwargs):
    """
    Adding mime-type to uploaded file (for future use).
    Would be called on post-save.
    """
    if not hasattr(instance, 'mime') or not hasattr(instance, 'file'):
        raise WrongObjectException("Object %s does not have 'mime' attribute! Can't set mime-type!" % instance)
    if instance.file:
        extension = os.path.splitext(instance.file.path)[1].lower()
        instance.set_mime(mimetypes.types_map[extension])
        #instance.save()

def make_slug(instance, **kwargs):
    """
    Set random hash as slug for unnamed items.
    """
    if not hasattr(instance, 'slug'):
        raise WrongObjectException("Object %s does not have slug attribute! Can't set random slug!" % instance)
    if not instance.slug:
        if hasattr(instance, 'name') and instance.name:
            instance.slug = slugify(instance.name)
        else:
            instance.slug = make_hash()

def default_variant_fix(instance, **kwargs):
    """
    If variant has default flag we need to check if parent item has other variants
    with default flag and fix them.
    """
    if not instance.default:
        return
    defaults = instance.parent.variant_set.filter(default=True).exclude(pk=instance.id)
    if len(defaults) > 0:
        for v in defaults:
            v.default = False
            v.save()