mediatr /

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

from helpers import make_hash

# init mime types dict

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

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()

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.slug = slugify(
            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:
    defaults = instance.parent.variant_set.filter(default=True).exclude(
    if len(defaults) > 0:
        for v in defaults:
            v.default = False