Created
March 23, 2013 16:45
-
-
Save gladson/5228375 to your computer and use it in GitHub Desktop.
Slug - Signals - Django
This file contains hidden or 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 import models | |
from django.db.models import signals | |
from signals import create_slug | |
class Category(models.Model): | |
name = models.CharField(u'nome', max_length=100) | |
slug = models.SlugField(max_length=150, editable=False) | |
slug_field_name = 'slug' | |
slug_from = 'name' | |
def __unicode__(self): | |
return self.name | |
class Meta: | |
verbose_name = u'categoria' | |
verbose_name_plural = u'categorias' | |
# Signals | |
signals.post_save.connect(create_slug, sender=Category) |
This file contains hidden or 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.template.defaultfilters import slugify | |
def create_slug(sender, instance, signal, *args, **kwargs): | |
if instance.id and hasattr(instance, 'slug_field_name') and hasattr(instance, 'slug_from'): | |
slug_name = instance.slug_field_name | |
slug_from = instance.slug_from | |
if not getattr(instance, slug_name, None): | |
slug = '%s-' % instance.id + slugify(getattr(instance, slug_from)) | |
setattr(instance, slug_name, slug) | |
instance.save() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks, it worked well