Mikhail Korobov  committed d0a4179

Allow populate_from to be callable

  • Participants
  • Parent commits d0933d7

Comments (0)

Files changed (2)

+#eclipse files
+syntax: glob

File autoslug/

     (`unique_with`) or globally (`unique`) and adding a number to the slug to make
     it unique.
-    :param populate_from: string: name of attribute from which to fill the slug.
+    :param populate_from: string or callable: if string is given it is considered as 
+        a name of attribute from which to fill the slug. If callable is given it should 
+        accept `instance` parameter and return a value to fill the slug with.
     :param unique: boolean: ensure total slug uniqueness (unless more precise `unique_with`
         is defined).
     :param unique_with: string or tuple of strings: name or names of attributes
         # minimum date granularity is shifted from day to month
         slug = AutoSlugField(populate_from='title', unique_with='pub_date__month')
+        # autoslugify value from models's user name using callable 
+        # ex. usage: user profile models
+        slug = AutoSlugField(populate_from=lambda instance: instance.user.get_full_name())
     def __init__(self, *args, **kwargs):
         kwargs['max_length'] = kwargs.get('max_length', 50)
         if value:
             slug = slugify(value)
         elif self.populate_from: # and not self.editable:
-            slug = slugify(getattr(instance, self.populate_from))
+            if callable(self.populate_from):
+                slug = slugify(self.populate_from(instance))
+            else:
+                slug = slugify(getattr(instance, self.populate_from))
             if __debug__ and not slug:
                 print 'Failed to populate slug %s.%s from an empty field %s' % \
                     (instance._meta.object_name,, self.populate_from)