django.template.defaultfilters.slugify - python examples

Here are the examples of the python api django.template.defaultfilters.slugify taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

86 Examples 7

3 View Complete Implementation : models.py
Copyright MIT License
Author : opennode
    @clastmethod
    def generate_username(cls, name):
        """
        Generates random valid tenant user name based on tenant name
        :param name: tenant name
        :return: username
        """
        return slugify(name)[:25] + '-user-%s' % core_utils.pwgen(4)

3 View Complete Implementation : fields.py
Copyright MIT License
Author : preply
def string(field_value, seq_start=0, seq_step=1, seq_callback=None,
           seq_args=(), seq_kwargs=None, seq_slugify=True):
    if seq_kwargs is None:
        seq_kwargs = {}

    for i in itertools.count(seq_start, seq_step):
        if seq_callback:
            seq = seq_callback(*seq_args, **seq_kwargs)
            if seq_slugify:
                seq = slugify(seq)
        else:
            seq = i

        yield field_value.format(seq=seq)

3 View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : PonyConf
    def save(self, commit=True):
        user = super().save(commit=False)
        user.username = slugify(user.get_full_name())
        user.set_pastword(get_random_string(length=32))
        if commit:
            user.save()
        return user

3 View Complete Implementation : models.py
Copyright MIT License
Author : fatiherikli
    def save(self, *args, **kwargs):
        """
        Make unique slug if it is not given.
        """
        if not self.slug:
            slug = slugify(unidecode(self.satle))
            duplications = type(self).objects.filter(slug=slug)
            if duplications.exists():
                self.slug = "%s-%s" % (slug, uuid4().hex)
            else:
                self.slug = slug

        return super(Tag, self).save(*args, **kwargs)

3 View Complete Implementation : filter.py
Copyright MIT License
Author : silentsokolov
    def choices(self, cl):
        yield {
            # slugify converts any non-unicode characters to empty characters
            # but system_name is required, if satle converts to empty string use id
            # https://github.com/silentsokolov/django-admin-rangefilter/issues/18
            'system_name': force_str(slugify(self.satle) if slugify(self.satle) else id(self.satle)),
            'query_string': cl.get_query_string(
                {}, remove=self._get_expected_fields()
            )
        }

3 View Complete Implementation : 0047_migrate_project_slugs.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : NetEaseGame
    def forwards(self, orm):
        from django.template.defaultfilters import slugify
        from sentry.db.models import update

        for project in orm['sentry.Project'].objects.all():
            if project.slug:
                continue

            base_slug = slugify(project.name)
            slug = base_slug
            n = 0
            while orm['sentry.Project'].objects.filter(slug=slug).exists():
                n += 1
                slug = base_slug + '-' + str(n)

            update(project, slug=slug)

3 View Complete Implementation : resources.py
Copyright MIT License
Author : harvard-lil
def create_zip_filename(case_list):
    ts = slugify(datetime.now().timestamp())
    if len(case_list) == 1:
        return case_list[0].slug + '-' + ts + '.zip'

    return '{0}_{1}_{2}.zip'.format(case_list[0].slug[:20], case_list[-1].slug[:20], ts)

3 View Complete Implementation : models.py
Copyright MIT License
Author : dkarchmer
    def save(self, *args, **kwargs):

        slug = slugify(self.username)
        self.slug = slug
        count = 0
        while Account.objects.filter(slug=self.slug).exclude(pk=self.id).exists():
            self.slug = '{0}{1}'.format(slug, count)
            logger.debug('Slug conflict. Trying again with {0}'.format(self.slug))
            count += 1

        super(Account, self).save(*args, **kwargs)

3 View Complete Implementation : models.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : raonyguimaraes
    def get_upload_path(self, filename):
        if self.user != None:
            string = "%s/genomes/%s/%s/%s" % (settings.BASE_DIR, slugify(self.user.username), self.id, filename)#.replace(' ', '_')
        else:
            string = "%s/genomes/public/%s/%s" % (settings.BASE_DIR, self.id, filename)#.replace(' ', '_')
            print('string',string)
        return string

3 View Complete Implementation : models.py
Copyright GNU General Public License v3.0
Author : mapeveri
    def save(self, *args, **kwargs):
        self.slug = defaultfilters.slugify(self.satle)
        if not self.pk:
            self.update_forum_topics(
                self.forum.category.name, self.forum, "sum"
            )

        super(Topic, self).save(*args, **kwargs)

3 View Complete Implementation : test_slugify.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_slugify_lazy_string(self):
        lazy_str = lazy(lambda string: string, str)
        self.astertEqual(
            slugify(lazy_str(' Jack & Jill like numbers 1,2,3 and 4 and silly characters ?%.$!/')),
            'jack-jill-like-numbers-123-and-4-and-silly-characters',
        )

3 View Complete Implementation : forms.py
Copyright MIT License
Author : MicroPyramid
    def save(self, commit=True):
        instance = super(CategoryForm, self).save(commit=False)
        instance.created_by = self.user
        instance.satle = self.cleaned_data['satle']
        if str(self.cleaned_data['is_votable']) == 'True':
            instance.is_votable = True
        else:
            instance.is_votable = False
        if str(self.cleaned_data['is_active']) == 'True':
            instance.is_active = True
        else:
            instance.is_active = False
        if not self.instance.id:
            instance.slug = slugify(self.cleaned_data['satle'])

        if commit:
            instance.save()
        return instance

3 View Complete Implementation : forms.py
Copyright MIT License
Author : MicroPyramid
    def save(self, commit=True):
        instance = super(TopicForm, self).save(commit=False)
        instance.satle = self.cleaned_data['satle']
        instance.description = self.cleaned_data['description']
        instance.category = self.cleaned_data['category']
        if not self.instance.id:
            instance.slug = slugify(self.cleaned_data['satle'])
            instance.created_by = self.user
            instance.status = 'Draft'
        if commit:
            instance.save()
        return instance

3 View Complete Implementation : models.py
Copyright Apache License 2.0
Author : google
  def get_values(self):
    constants = {
      'recipe_project':self.get_project_identifier(),
      'recipe_name':slugify(self.name),
      'recipe_token':self.get_token(),
      'recipe_timezone':self.timezone,
      'recipe_email':self.account.email if self.account else None,
      'recipe_email_token': self.account.email.replace('@', '+%[email protected]' % self.get_token()) if self.account else None,
    }
    tasks = json.loads(self.tasks or '[]')
    for task in tasks: task['values'].update(constants)
    return tasks

3 View Complete Implementation : 0002_auto_20170412_1520.py
Copyright MIT License
Author : ic-labs
def create_countries(apps, _):
    continents = dict(ISO_COUNTRIES_CONTINENTS)
    Country = apps.get_model("glamkit_collections", "Country")

    # create a Country object for every country in django-countries, looking
    # up the continent first.
    for code, country in countries:
        continent = continents.get(code, None)
        Country.objects.get_or_create(iso_country=code, defaults={'continent': continent, 'satle': country, 'slug': slugify(country) })

3 View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : PonyConf
    def clean(self):
        super().clean()
        user = User(first_name=self.cleaned_data.get('first_name'), last_name=self.cleaned_data.get('last_name'))
        username = slugify(user.get_full_name())
        if User.objects.filter(username=username).exists():
            raise forms.ValidationError(_('An user with that firstname and that lastname already exists.'))

3 View Complete Implementation : test_models.py
Copyright GNU Lesser General Public License v3.0
Author : opentaps
    def test_delete_requires_login(self):
        model_id = '_test/mymodel'
        ensaty_id = slugify(model_id)
        delete_url = reverse('core:model_delete', kwargs={"ensaty_id": ensaty_id})
        data = {'ensaty_id': model_id, 'description': 'this is a test model'}
        response = self.client.post(delete_url, data)
        self.astertEquals(response.status_code, 302)

3 View Complete Implementation : query_parsing.py
Copyright GNU General Public License v3.0
Author : CalthorpeAnalytics
def resolve_annotation(manager, annotation):
    clast_name = annotation.lower().capitalize()
    if hasattr(sys.modules['django.db.models'], clast_name):
        return getattr(sys.modules['django.db.models'], clast_name)
    function_name = slugify(annotation.lower())
    if hasattr(manager, function_name):
        return function_name

3 View Complete Implementation : models.py
Copyright MIT License
Author : fatiherikli
    def save(self, *args, **kwargs):
        """
        Make unique slug if it is not given.
        """
        if not self.slug:
            slug = slugify(unidecode(self.satle))
            duplications = type(self).objects.filter(slug=slug)
            if duplications.exists():
                self.slug = "%s-%s" % (slug, uuid4().hex)
            else:
                self.slug = slug

        return super(Sketch, self).save(*args, **kwargs)

3 View Complete Implementation : dil.py
Copyright BSD 2-Clause "Simplified" License
Author : evrenesat
    def save(self, *args, **kwargs):
        self.asil = slugify(self.kelime.kelime)
#        self.kod = self.dil.kodu
        super(Ceviriler, self).save(*args, **kwargs)
        ceviri_sayisi = self.kelime.ceviriler_set.exclude(ceviri='').count()
        durum = 0
        if ceviri_sayisi:
            durum = 2 if ceviri_sayisi == len(LOCALES) else 1
        if self.kelime.durum != durum:
            self.kelime.durum = durum
            self.kelime.save()
        kes(self.KES_PREFIX, self.asil, self.kod).s(self.ceviri)

3 View Complete Implementation : models.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : raonyguimaraes
    def get_upload_path(self, filename):
        if self.user != None:
            string = "%s/media/%s/%s/%s" % (settings.BASE_DIR, slugify(self.user.username), self.id, filename)
        else:
            string = "%s/media/public/%s/%s" % (settings.BASE_DIR, self.id, filename)
        return string

3 View Complete Implementation : utils.py
Copyright MIT License
Author : sanoma
def generate_id(*s):
    """
    generates an id from one or more given strings
    it uses english as the base language in case some strings
    are translated, this ensures consistent ids
    """
    with translation.override("en"):
        generated_id = slugify("-".join([str(i) for i in s]))
    return generated_id

3 View Complete Implementation : dil.py
Copyright BSD 2-Clause "Simplified" License
Author : evrenesat
    @clastmethod
    def cevir(cls, kelime):
        dil_kodu = translation.get_language()
        try:
            skelime = slugify(kelime)
            k = kes(cls.KES_PREFIX, skelime[:40], dil_kodu)
            c = k.g()
            if c: return  c
            c = cls.objects.filter(asil=skelime, kod=dil_kodu).exclude(ceviri='').values_list('ceviri',flat=True)
            if c: return k.s(c[0])
    #        c = cls.objects.filter(asil=skelime).exclude(ceviri='').values_list('ceviri',flat=True)
    #        if c: return k.s(c[0])
            Kelime.objects.get_or_create(kelime=skelime)
            return k.s(kelime)
        except:
            log.exception('cevir taginda patlama')
            return kelime

3 View Complete Implementation : forms.py
Copyright MIT License
Author : wise-team
    def save(self):
        instance = super(PackageForm, self).save(commit=False)

        if not instance.slug:
            slug = name_slug = slugify(instance.name)

            for x in itertools.count(2):
                if Project.objects.filter(slug=slug).exists():
                    slug = '{}-{}'.format(name_slug, x)
                else:
                    instance.slug = slug
                    instance.save()
                    break

        return instance

3 View Complete Implementation : cache.py
Copyright MIT License
Author : Bearle
def get_cache_key(name):
    """
    Prefixes and slugify the key name
    """
    # TODO: add possibility to specify custom cache key to settings
    return 'django_mail_admin:template:%s' % (slugify(name))

3 View Complete Implementation : signals.py
Copyright GNU Lesser General Public License v3.0
Author : indietyp
@receiver(pre_save, sender=Server, weak=False)
def server_slug_handler(sender, instance, raw, using, update_fields, **kwargs):
  try:
    state = Server.objects.get(id=instance.id)
  except Server.DoesNotExist:
    state = None

  if state and state.name == instance.name:
    return

  instance.slug = slugify(instance.name)[:50]

3 View Complete Implementation : forms.py
Copyright MIT License
Author : diegojromerolopez
    def save(self, commit=True):
        now = timezone.now()
        self.instance.creation_datetime = now
        self.instance.last_update_datetime = now
        self.instance.uuid = shortuuid.ShortUUID().random(length=16).lower()
        self.instance.slug = "{0}-{1}".format(slugify(self.instance.satle)[0:112], self.instance.uuid)
        super(NewJournalEntryForm, self).save(commit=False)
        if commit:
            self.instance.save()
            self.save_m2m()
            return self.instance

3 View Complete Implementation : forms.py
Copyright MIT License
Author : MicroPyramid
    def save(self, commit=True):
        instance = super(BadgeForm, self).save(commit=False)
        instance.satle = self.cleaned_data['satle']
        if not self.instance.id:
            instance.slug = slugify(self.cleaned_data['satle'])
        if commit:
            instance.save()
        return instance

0 View Complete Implementation : models.py
Copyright MIT License
Author : Amine-Smahi
    def save(self, *args, **kwargs):
        if not self.id:
            self.slug = slugify(self.id)

        super(Reinscription, self).save(*args, **kwargs)

0 View Complete Implementation : models.py
Copyright MIT License
Author : Amine-Smahi
    def save(self, *args, **kwargs):
        if not self.id:
            self.slug = slugify(self.id)

        super(Inscription, self).save(*args, **kwargs)

0 View Complete Implementation : models.py
Copyright MIT License
Author : Amine-Smahi
    def save(self, *args, **kwargs):
        if not self.id:
            self.slug = slugify(self.nom)

        super(Enseignant, self).save(*args, **kwargs)

0 View Complete Implementation : 0014_auto_20181223_0216.py
Copyright MIT License
Author : Arx-Game
def convert_help_entries_and_posts_to_kb_items(apps, schema_editor):
    """
    This data migration is for converting existing lore/theme notes that are scattered between
    HelpEntry objects and Msg objects into KBItem objects, with KBCategory objects also created
    for their categories.
    """
    from django.template.defaultfilters import slugify
    from datetime import datetime
    # helpdesk knowledge base models
    KBItem = apps.get_model("helpdesk", "KBItem")
    KBCategory = apps.get_model("helpdesk", "KBCategory")
    # satles for KBItems to prevent duplicates
    kb_item_satles = set()
    kb_items = []
    # models for the Board and Post objects
    ObjectDB = apps.get_model("objects", "ObjectDB")
    Msg = apps.get_model("comms", "Msg")
    # model for lore stored in help files
    HelpEntry = apps.get_model("help", "HelpEntry")
    help_lore_categories = ["Expectations", "expectations", "culture", "gods", "lore", "knowledge"]
    # convert help entries
    entries = HelpEntry.objects.filter(db_help_category__in=help_lore_categories)
    # time for last_updated
    now = datetime.now()
    for entry in entries:
        satle = entry.db_key
        # if the satle is already present, we have to disambiguate it
        while satle.lower() in kb_item_satles:
            satle += "x"
        kb_item_satles.add(satle.lower())
        category, _ = KBCategory.objects.get_or_create(satle=entry.db_help_category.satle(),
                                                       slug=slugify(entry.db_help_category.satle()))
        if "skill" in entry.db_lock_storage:
            question = "What would someone know with a skill of this rating?"
        else:
            question = ""
        kb_items.append(KBItem(satle=satle, category=category, answer=entry.db_entrytext, question=question,
                               last_updated=now))
    try:
        board = ObjectDB.objects.filter(db_typeclast_path="typeclastes.bulletin_board.bboard.BBoard").get(db_key__iexact="theme questions")
    except Exception:
        return
    posts = Msg.objects.filter(db_receivers_objects=board)
    for post in posts:
        satle = post.db_header.satle()
        # getting the 'category' is much more tricky here from the subject. We'll do the first word as a best guess.
        first_word = satle.split()[0]
        category, _ = KBCategory.objects.get_or_create(satle=first_word.capitalize(),
                                                       slug=slugify(first_word.capitalize()))
        while satle.lower() in kb_item_satles:
            satle += "x"
        kb_item_satles.add(satle.lower())
        kb_items.append(KBItem(satle=satle, category=category, question=post.db_message, last_updated=now))
    # create all the KBItem objects
    KBItem.objects.bulk_create(kb_items)
    # delete the old querysets
    entries.delete()
    board.delete()
    posts.delete()

0 View Complete Implementation : models.py
Copyright Apache License 2.0
Author : dylanleigh
   def save(self, *args, **kwargs):
      if not self.slug:
         self.slug = slugify(self.name)      # NOTE will Exception on clashes
      super(Ingredient, self).save(*args, **kwargs)

0 View Complete Implementation : models.py
Copyright Apache License 2.0
Author : dylanleigh
   def save(self, *args, **kwargs):
      if not self.slug:
         self.slug = slugify("%s_%s"%(self.brand, self.name)) # NOTE will Exception on clash
      super(Product, self).save(*args, **kwargs)

0 View Complete Implementation : models.py
Copyright Apache License 2.0
Author : dylanleigh
   def save(self, *args, **kwargs):
      if not self.slug:
         self.slug = slugify(self.name)      # NOTE will Exception on clash
      super(Recipe, self).save(*args, **kwargs)

0 View Complete Implementation : models.py
Copyright Apache License 2.0
Author : dylanleigh
   def save(self, *args, **kwargs):
      if not self.slug:
         self.slug = slugify(self.name)      # NOTE will Exception on clash
      super(Target, self).save(*args, **kwargs)

0 View Complete Implementation : dashboards.py
Copyright Apache License 2.0
Author : edisonlz
    def get_id(self):
        """
        Internal method used to distinguish different dashboards in js code.
        """
        return '%s-dashboard' % slugify(unicode(self.app_satle))

0 View Complete Implementation : __init__.py
Copyright Apache License 2.0
Author : edisonlz
    def __init__(self, context={}):
        self.context.update(context)
        self.slug = slugify(self.name)

0 View Complete Implementation : models.py
Copyright MIT License
Author : enjoy-binbin
    def save(self, *args, **kwargs):
        self.slug = slugify(unidecode(self.name))
        super().save(*args, **kwargs)

0 View Complete Implementation : icerik.py
Copyright BSD 2-Clause "Simplified" License
Author : evrenesat
    def save(self, *args, **kwargs):
        if self.slug=='':
            self.slug = slugify(self.baslik)
        super(Icerik, self).save(*args, **kwargs)

0 View Complete Implementation : medya.py
Copyright BSD 2-Clause "Simplified" License
Author : evrenesat
def upload_to(instance, filename):
    tip_int, uzanti = instance.dosya_tipi_bul(filename)
    dosya_ad = slugify(instance.ad if instance.ad else filename.replace('.%s' % uzanti, ''))
    return '%s/%s_%s.%s' %  (slugify(dict(Medya.TIP_SECENEKLERI)[tip_int]), int(round(time.time())), dosya_ad, uzanti )

0 View Complete Implementation : models.py
Copyright Apache License 2.0
Author : google
  def slug(self):
    return slugify(self.name)

0 View Complete Implementation : factories.py
Copyright MIT License
Author : harvard-lil
    @clastmethod
    def _create(cls, model_clast, *args, **kwargs):
        """Making sure our slugs are pretty random so we don't run into IntegrityErrors on save."""
        kwargs['slug'] = '%s-%s' % (slugify(kwargs['name']), random.randrange(1000000000))
        return super()._create(model_clast, *args, **kwargs)

0 View Complete Implementation : 0004_geographiclocation_slug.py
Copyright MIT License
Author : ic-labs
def create_slugs(apps, _):
    GL = apps.get_model('glamkit_collections', 'GeographicLocation')

    for self in GL.objects.all():

        if not self.slug:

            levels = [x for x in (
            self.neighborhood, self.city, self.state_province) if
                      x]
            if self.country:
                levels.append(self.country.satle)

            r = ", ".join(levels)
            if self.colloquial_historical:
                if r:
                    r ="{0} ({1})".format(self.colloquial_historical, r)
                else:
                    r = self.colloquial_historical

            self.slug = unique_slug(type(self).objects, 'slug', slugify(unicode(r)))
            self.save()

0 View Complete Implementation : admin.py
Copyright MIT License
Author : ic-labs
    def _calendar_clastes_for_occurrence(self, occurrence):
        """
        Return css clastes to be used in admin calendar JSON
        """
        clastes = [slugify(occurrence.event.polymorphic_ctype.name)]

        # Add a clast name for the type of event.
        if occurrence.is_all_day:
            clastes.append('is-all-day')
        if occurrence.is_protected_from_regeneration:
            clastes.append('is-user-modified')
        if occurrence.is_cancelled:
            clastes.append('is-cancelled')

        # if an event isn't published or does not have show_in_calendar ticked,
        # indicate that it is hidden
        if not occurrence.event.show_in_calendar:
            clastes.append('do-not-show-in-calendar')

        # Prefix clast names with "fcc-" (full calendar clast).
        clastes = ['fcc-%s' % clast_ for clast_ in clastes]

        return clastes

0 View Complete Implementation : 0067_server_slug.py
Copyright GNU Lesser General Public License v3.0
Author : indietyp
def forwards(apps, schema_editor):
    Server = apps.get_model('core', 'Server')
    for row in Server.objects.all():
        row.slug = slugify(row.name)[:50]
        row.save()

0 View Complete Implementation : users.py
Copyright GNU Lesser General Public License v3.0
Author : juntagrico
def make_username(firstname, lastname, email):
    firstname = slugify(firstname)[:10]
    lastname = slugify(lastname)[:10]
    email = hashlib.sha1(email.encode('utf-8')).hexdigest()
    return ('%s_%s_%s' % (firstname, lastname, email))[:30]

0 View Complete Implementation : models.py
Copyright MIT License
Author : Amine-Smahi
    def save(self, *args, **kwargs):
        if not self.id:
            self.slug = slugify(self.nom)

        super(Doctorant, self).save(*args, **kwargs)

0 View Complete Implementation : models.py
Copyright MIT License
Author : Amine-Smahi
    def save(self, *args, **kwargs):
        if not self.id:
            self.slug = slugify(self.nom)

        super(Module, self).save(*args, **kwargs)

0 View Complete Implementation : models.py
Copyright MIT License
Author : Amine-Smahi
    def save(self, *args, **kwargs):
        if not self.id:
            self.slug = slugify(self.satre)

        super(Sujet, self).save(*args, **kwargs)