Created
December 22, 2011 14:27
-
-
Save ojii/1510473 to your computer and use it in GitHub Desktop.
auto-slug class decorator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from django.db.models.signals import pre_save | |
from django.template.defaultfilters import slugify | |
class Slugifier(object): | |
def __init__(self, model, target, source): | |
self.model = model | |
self.target = target | |
self.source = source | |
field = self.model._meta.get_field_by_name(self.target)[0] | |
self.max_length = field.max_length | |
def __call__(self, instance, **kwargs): | |
if getattr(instance, self.target): | |
return | |
slug = slugify(getattr(instance, self.source))[:self.max_length] | |
current = slug | |
index = 0 | |
while self.model.objects.filter(**{self.target: current}).exists(): | |
suffix = '-%s' % index | |
current = '%s%s' % (slug[:-len(suffix)], suffix) | |
index += 1 | |
setattr(instance, self.target, current) | |
def auto_slug(target, source): | |
""" | |
@auto_slug('slug', 'name') | |
class MyModel(models.Model): | |
name = models.CharField(max_length=255) | |
slug = models.SlugField(max_length=255, null=True) | |
""" | |
def _decorator(cls): | |
pre_save.connect(Slugifier(cls, target, source), sender=cls, weak=False) | |
return cls | |
return _decorator |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment