'Generate a unique slug for a model instance.'

def create_slug(self, model_instance):

    slug_field = model_instance._meta.get_field(self.attname)
    slug = self.slugify(getattr(model_instance, self._populate_from))
    count = 0
    slug_len = slug_field.max_length
    if slug_len:
        slug = slug[:slug_len]
    original_slug = slug
    queryset = self.get_queryset(model_instance.__class__, slug_field)
    if model_instance.pk:
        queryset = queryset.exclude(pk=model_instance.pk)
    kwargs = {}
    for params in model_instance._meta.unique_together:
        if (self.attname in params):
            for param in params:
                kwargs[param] = getattr(model_instance, param, None)
    kwargs[self.attname] = slug
    while ((not slug) or queryset.filter(**kwargs)):
        slug = original_slug
        end = self.uniquifying_suffix(count)
        end_len = len(end)
        if (slug_len and ((len(slug) + end_len) > slug_len)):
            slug = slug[:(slug_len - end_len)]
        slug = (slug + end)
        kwargs[self.attname] = slug
        count += 1
    assert self.test_pattern.match(slug), 'Invalid    generated    slug:    {slug}'.format(slug=slug)
    return slug
