Automatic slug generation signal

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from django.template.defaultfilters import slugify

def find_available_slug(object, instance, slug):
    """
    Recursive method that will add underscores to a slug field
    until a free value is located
    """
    try:
        sender_node = object.objects.get(slug=slug)
    except object.DoesNotExist:
        instance.slug = slug
    else:
        slug = '%s_' % slug
        find_available_slug(object, instance, slug)
    return

def slug_generator(sender, **kwargs):
    """ Generates a unique slug for a node """
    instance = kwargs['instance']
    if instance.slug is not '':
        return
    slug = slugify(instance.title)
    find_available_slug(sender, instance, slug)

More like this

  1. REMOVE IMAGEFIELD ATTACHMENT IN DJANGO by timonweb 1 year ago
  2. Signal to notify new saved comments by arthurfurlan 3 years, 11 months ago
  3. "Autoconnect" model decorator, easy pre_save and post_save signal connection by bendavis78 2 years, 10 months ago
  4. Signal to post new saved objects to Twitter by arthurfurlan 4 years, 2 months ago
  5. Unique Slugify by SmileyChris 5 years, 1 month ago

Comments

(Forgotten your password?)