Returns a new unique slug. Object must provide a SlugField called slug.
    URL friendly slugs are generated using django.template.defaultfilters' slugify.
    Numbers are added to the end of slugs for uniqueness.
970013
def generate_slug(obj, text, tail_number=0):
    from panya.models import ModelBase
    
    # use django slugify filter to slugify
    slug = slugify(text)
    
    existing_slugs = [item.slug for item in ModelBase.objects.filter(slug__regex=r'^%s(-\d+)?' % slug).exclude(id=obj.id)]
    
    tail_number = 0
    new_slug = slug
    while new_slug in existing_slugs:
        new_slug = slugify("%s-%s" % (slug, tail_number))
        tail_number += 1
    
    return new_slug
706238
def gen_unique_id():
    
    # Workaround for http://bugs.python.org/issue4607
    if ctypes and _uuid_generate_random:
        buffer = ctypes.create_string_buffer(16)
        _uuid_generate_random(buffer)
        return str(UUID(bytes=buffer.raw))
    return str(uuid4())
1154388
public function regenerateSlug()
    {
        $this->slugWorkingRecord->{$this->slugDbField} = $this->encrypt();
        $salt = $this->slugSalt;

        if ($this->mustBeUnique && !$this->hasUniqueSlug()) {
            $generator = new RandomGenerator();

            while (!$this->hasUniqueSlug()) {
                $salt = $generator->randomToken();
                $this->slugWorkingRecord->{$this->slugDbField} = $this->encrypt(null, $salt);
            }
        }

        $this->slugWorkingRecord->{$this->slugDbFieldForSalt} = $salt;
    }
891018
private function add_slugify_helper() {
		$this->engine->addHelper(
			'slugify',
			function ( $template, $context, $args ) {
					$arg = $context->get( $args );
					return slugify( $arg );
			}
		);
	}
515030
def get_instance_by_slug(model, slug, **kwargs):
    
    try:
        model = get_model(model)
    except ImportError:
        return None

    query_params = dict(kwargs)
    query_params['slug'] = slug

    return model.query.filter_by(**query_params).first()
763262
def is_slug_available(self, slug, **kwargs):
        
        try:
            self.get(slug=slug, **kwargs)
            return False
        except self.model.DoesNotExist:
            return True
1292190
def _generate_slug(self, value):
        
        alphabet = app_settings.SLUG_ALPHABET
        salt = app_settings.SLUG_SALT

        hashids = Hashids(alphabet=alphabet, salt=salt, min_length=5)

        return hashids.encode(value)
1314403
def slug_exists(self, request):
        
        if not request.user.is_authenticated:
            return Response(status=status.HTTP_401_UNAUTHORIZED)

        if 'name' not in request.query_params:
            return Response({'error': 'Query parameter `name` must be given.'},
                            status=status.HTTP_400_BAD_REQUEST)

        queryset = self.get_queryset()
        slug_name = request.query_params['name']
        return Response(queryset.filter(slug__iexact=slug_name).exists())
909987
def get_one(slug):
    
    item = Product.objects.published()\
        .prefetch_related(Prefetch("paramvalue_set", queryset=ParamValue.objects.published().order_by('sort').prefetch_related("param")))\
        .filter(slug=slug).first()
    return item
422047
def pre_save(self, instance, add):
        
        # get currently entered slug
        value = self.value_from_object(instance)
        slug = None

        # auto populate (if the form didn't do that already).
        # If you want unique_with logic, use django-autoslug instead.
        # This model field only allows parameters which can be passed to the form widget too.
        if self.populate_from and (self.always_update or not value):
            value = getattr(instance, self.populate_from)

        # Make sure the slugify logic is applied,
        # even on manually entered input.
        if value:
            value = force_text(value)
            slug = self.slugify(value)
            if self.max_length < len(slug):
                slug = slug[:self.max_length]

        # make the updated slug available as instance attribute
        setattr(instance, self.name, slug)
        return slug
597195
def generate_slug(value):
    
    alphabet = app_settings.SLUG_ALPHABET
    salt = app_settings.SLUG_SALT

    hashids = Hashids(alphabet=alphabet, salt=salt, min_length=5)

    return hashids.encode(value)
273969
def pre_save(self, instance, add):
        """"""
        slug = self.value_from_object(instance)

        # We don't want to change slug defined by user.
        predefined_slug = bool(slug)

        if not slug and self.populate_from:
            slug = self._get_populate_from_value(instance)

        if slug:
            slug = slugify(slug)

        if not slug:
            slug = None

            if not self.blank:
                slug = instance._meta.model_name  # pylint: disable=protected-access
            elif not self.null:
                slug = ''

        if slug:
            # Make sure that auto generated slug with added sequence
            # won't excede maximal length.
            # Validation of predefined slugs is handled by Django.
            if not predefined_slug:
                slug = slug[:(self.max_length - MAX_SLUG_SEQUENCE_DIGITS - 1)]

            constraints_placeholder, constraints_values = self._get_unique_constraints(instance)

            instance_pk_name = instance._meta.pk.name  # pylint: disable=protected-access

            # Safe values - make sure that there is no chance of SQL injection.
            query_params = {
                'constraints_placeholder': constraints_placeholder,
                'slug_column': connection.ops.quote_name(self.column),
                'slug_len': len(slug),
                'table_name': connection.ops.quote_name(self.model._meta.db_table),  # pylint: disable=protected-access
                'pk_neq_placeholder': 'AND {} != %(instance_pk)s'.format(instance_pk_name) if instance.pk else ''
            }

            # SQL injection unsafe values - will be escaped.
            # Keys prefixed with `unique_` are reserved for `constraints_values` dict.
            query_escape_params = {
                'slug': slug,
                'slug_regex': '^{}(-[0-9]*)?$'.format(slug),
            }
            query_escape_params.update(constraints_values)
            if instance.pk:
                query_escape_params['instance_pk'] = instance.pk

            with connection.cursor() as cursor:
                # TODO: Slowest part of this query is `MAX` function. It can
                #       be optimized by indexing slug column by slug sequence.
                #       https://www.postgresql.org/docs/9.4/static/indexes-expressional.html
                cursor.execute(
                    """
                    SELECT
                        CASE
                            WHEN (
                                EXISTS(
                                    SELECT 1 FROM {table_name} WHERE (
                                        {slug_column} = %(slug)s
                                        {pk_neq_placeholder}
                                        {constraints_placeholder}
                                    )
                                )
                            ) THEN MAX(slug_sequence) + 1
                            ELSE NULL
                        END
                    FROM (
                        SELECT COALESCE(
                            NULLIF(
                                RIGHT({slug_column}, -{slug_len}-1),
                                ''
                            ),
                            '1'
                        )::text::integer AS slug_sequence
                        FROM {table_name} WHERE (
                            {slug_column} ~ %(slug_regex)s
                            {pk_neq_placeholder}
                            {constraints_placeholder}
                        )
                    ) AS tmp
                    """.format(**query_params),
                    params=query_escape_params
                )
                result = cursor.fetchone()[0]

            if result is not None:
                if predefined_slug:
                    raise SlugError(
                        "Slug '{}' (version {}) is already taken.".format(slug, instance.version)
                    )

                if len(str(result)) > MAX_SLUG_SEQUENCE_DIGITS:
                    raise SlugError(
                        "Auto-generated slug sequence too long - please choose a different slug."
                    )

                slug = '{}-{}'.format(slug, result)

            # Make the updated slug available as instance attribute.
            setattr(instance, self.name, slug)

        return slug
1053955
def generate(self, pattern=None):
        
        lst = self._lists[pattern]
        while True:
            result = lst[self._randrange(lst.length)]
            # 1. Check that there are no duplicates
            # 2. Check that there are no duplicate prefixes
            # 3. Check max slug length
            n = len(result)
            if (self._ensure_unique and len(set(result)) != n or
                    self._check_prefix and len(set(x[:self._check_prefix] for x in result)) != n or
                    self._max_slug_length and sum(len(x) for x in result) + n - 1 > self._max_slug_length):
                continue
            return result
252626
def update_urlname!
      new_urlname = nested_url_name(slug)
      if urlname != new_urlname
        legacy_urls.create(urlname: urlname)
        update_column(:urlname, new_urlname)
      end
    end
1018577
def clean_slug(self):
        
        slug = self.cleaned_data.get('slug', None)
        if slug is None or len(slug) == 0 and 'title' in self.cleaned_data:
            slug = slugify(self.cleaned_data['title'])
        return slug
1257626
def slugify(self, name):
        
        slug = ''
        last = ''
        for char in name.replace('#', '').lower().strip():
            if not char.isalnum():
                char = '_'

            if last == '_' and char == '_':
                continue

            slug += char
            last = char

        return slug
1159233
def get_object(self, queryset=None):
        

        schema = manager.get_schema()
        vid = None
        if self.request.GET.get('vid') and self.request.user.is_staff and \
                self.request.user.is_active:
            try:
                schema = 'public'
                vid = int(self.request.GET.get('vid'))
                queryset = self.model.normal.filter(vid=vid)
            except ValueError:
                pass

        with manager.SwitchSchema(schema):
            # Use a custom queryset if provided
            if queryset is None:
                queryset = self.get_queryset()

            # Next, try looking up by primary key.
            pk = self.kwargs.get(self.pk_url_kwarg, None)
            slug = self.kwargs.get(self.slug_url_kwarg, None)
            if pk is not None:
                if vid:
                    queryset = queryset.filter(vid=vid)
                else:
                    queryset = queryset.filter(object_id=pk)

            # Next, try looking up by slug.
            elif slug is not None:
                slug_field = self.get_slug_field()
                queryset = queryset.filter(**{slug_field: slug})

            # If none of those are defined, it's an error.
            else:
                raise AttributeError(u"View %s must be called with "
                                     u"either an object pk or a slug."
                                     % self.__class__.__name__)

            try:
                obj = queryset.get()
            except queryset.model.DoesNotExist:
                raise http.Http404(
                        u"No %(verbose_name)s found matching the query" %
                         {'verbose_name': queryset.model._meta.verbose_name})

        return obj