django.template.defaultfilters.slugify

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.

200 Examples 7

Example 1

Project: pythondotorg
Source File: models.py
View license
    def save(self, **kwargs):
        location_parts = (self.city, self.region, self.country)
        location_str = ''
        for location_part in location_parts:
            if location_part is not None:
                location_str = ' '.join([location_str, location_part])
        self.location_slug = slugify(location_str)
        self.country_slug = slugify(self.country)

        if not self.expires and self.status == self.STATUS_APPROVED:
            delta = datetime.timedelta(days=settings.JOB_THRESHOLD_DAYS)
            self.expires = timezone.now() + delta

        return super().save(**kwargs)

Example 2

Project: qualitio
Source File: models.py
View license
    def save(self, *args, **kwargs):
        # significant part of this link is only ID, rest is only for information purposes.
        # Filter applayed to get rid root's empty path
        if not self.pk:
            super(Report, self).save(*args, **kwargs)

        link_elements = filter(lambda x:x, ['report/external',
                                            str(self.pk),
                                            slugify(self.parent.path),
                                            slugify(self.parent.name),
                                            slugify(self.name),
                                            self.created_time.strftime("%Y/%m/%d")])

        self.link = "%s%s" % (self.project.get_absolute_url(), "/".join(link_elements))
        kwargs['force_insert'] = False
        super(Report, self).save(*args, **kwargs)

Example 3

Project: readthedocs.org
Source File: forms.py
View license
    def clean_name(self):
        name = self.cleaned_data.get('name', '')
        if not self.instance.pk:
            potential_slug = slugify(name)
            if Project.objects.filter(slug=potential_slug).exists():
                raise forms.ValidationError(
                    _('Invalid project name, a project already exists with that name'))
        return name

Example 4

Project: brigitte
Source File: forms.py
View license
    def clean(self):
        slug = slugify(self.cleaned_data.get('title', ''))

        instance_pk = 0
        if self.instance:
            instance_pk = self.instance.pk

        if Repository.objects.filter(
            user=self.user,
            slug=slug
        ).exclude(
            pk=instance_pk
        ).count() > 0:
            raise forms.ValidationError('Repository name already in use.')

        return self.cleaned_data

Example 5

Project: django-mongoforms
Source File: models.py
View license
    def save(self):
        if self.slug is None:
            slug = slugify(self.title)
            new_slug = slug
            c = 1
            while True:
                try:
                    BlogPost.objects.get(slug=new_slug)
                except BlogPost.DoesNotExist:
                    break
                else:
                    c += 1
                    new_slug = '%s-%s' % (slug, c)
            self.slug = new_slug
        return super(BlogPost, self).save()

Example 6

Project: web
Source File: models.py
View license
    def document_file_name(instance, filename):
        """Where to put a newly uploaded document. Also, store original filename."""
        ext = os.path.splitext(filename)[1]
        timestamp = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
        instance.original_filename = filename
        return '/'.join(['documents', slugify(instance.category.name), '%s%s' % (timestamp, ext)])

Example 7

Project: amy
Source File: views.py
View license
    def get(self, request):
        try:
            url = request.GET['url']
            conf = requests.get(urljoin(url, 'api/')).json()
            return JsonResponse({
                'slug': slugify('{}-{}'.format(conf['start_date'], conf['title'])),
                'start': conf['start_date'],
                'end': conf['end_date'],
            })
        except KeyError:
            return HttpResponseBadRequest('Missing "url" parameter')
        except (requests.exceptions.RequestException, JSONDecodeError):
            return HttpResponseBadRequest('Conference site does not support an API')
        except Exception as e:
            return HttpResponseBadRequest(str(e))

Example 8

View license
def fix_project_template_slugs(apps, schema_editor):
    ProjectTemplate = apps.get_model("projects", "ProjectTemplate")
    for pt in ProjectTemplate.objects.all():
        for us_status in pt.us_statuses:
            us_status["slug"] = slugify(us_status["name"])
        for task_status in pt.task_statuses:
            task_status["slug"] = slugify(task_status["name"])
        for issue_status in pt.issue_statuses:
            issue_status["slug"] = slugify(issue_status["name"])
        pt.save()

Example 9

Project: Tango
Source File: helpers.py
View license
def get_vimeo_data(video):
    """
    Helper to extract video and thumbnail from vimeo.
    """
    #http://vimeo.com/67325705 -- Tumbleweed Tango
    video.source = 'vimeo'
    video.key = video.url.rsplit('/', 1)[1]
    video.embed_src = 'http://player.vimeo.com/video/'

    api_url = 'http://vimeo.com/api/v2/video/{}.xml'.format(video.key)
    video_data = urlopen(api_url).read()
    xml = xmltramp.parse(video_data)
    video.title = unicode(xml.video.title)
    video.slug = slugify(video.title)
    video.summary = unicode(xml.video.description)
    video.thumb_url = unicode(xml.video.thumbnail_large)
    return video

Example 10

Project: wagtail_blog
Source File: models.py
View license
    def save(self, *args, **kwargs):
        if not self.slug:
            slug = slugify(self.name)
            count = BlogCategory.objects.filter(slug=slug).count()
            if count > 0:
                slug = '{}-{}'.format(slug, count)
            self.slug = slug
        return super(BlogCategory, self).save(*args, **kwargs)

Example 11

Project: django-common
Source File: db_fields.py
View license
    def __unique_slug(self, model, model_instance, slug_field, slug_value):
        orig_slug = slug = slugify(slug_value)
        index = 1
        while True:
            try:
                model.objects.get(**{slug_field: slug})
                index += 1
                slug = orig_slug + '-' + str(index)
            except model.DoesNotExist:
                return self.__set_and_return(model_instance, slug_field, slug)

Example 12

Project: django-sluggable
Source File: models.py
View license
    def _generate_base_slug(self):
        """
        Generate the base slug for this model.
        
        If you'd like to use something other than this model's __unicode__
        representation to generate the base slug, override this method in your
        model class to return a slugified string.
        """
        return slugify(u'%s' % self)

Example 13

Project: django-superflatpages
Source File: models.py
View license
    def save(self, *args, **kwargs):
        message = kwargs.get('message', 'Auto-saved')
        
        if 'message' in kwargs:
            del(kwargs['message'])
        
        if not self.slug:
            self.slug = slugify(self.title)
            
        if not self.path:
            if self.parent:
                self.path = "/".join([self.parent.path, self.slug])
            else:
                self.path = self.slug
        
        self.modified = datetime.datetime.now()
        super(FlatPage, self).save(*args, **kwargs)
        FlatPageSnapshot.objects.create_snapshot(self, message=message)
        return self

Example 14

Project: django-unfriendly
Source File: tests.py
View license
    def test_obfuscate_filter_with_juice(self):
        """
        Test the obfuscate filter.
        """
        test_url = reverse('unfriendly-test')
        obfuscated_url = obfuscate(test_url, self.juice)
        view_url = reverse('unfriendly-deobfuscate', kwargs={
            'juice': slugify(self.juice),
            'key': encrypt(test_url, settings.UNFRIENDLY_SECRET,
                           settings.UNFRIENDLY_IV),
        })
        self.assertEqual(view_url, obfuscated_url)

Example 15

Project: treeio
Source File: models.py
View license
    def treewalk(self, save=True):
        "Walks up the tree to construct both Item treepath and item.name from database"
        slug = unicode(self.name).replace(" ", "-")
        slug = defaultfilters.slugify(unidecode(slug))
        treepath = slug + "/"

        self.treepath = treepath

        if save:
            self.save()
        return self

Example 16

Project: ProjectNarwhal
Source File: models.py
View license
    def save(self, **kwargs):
        #from markdown import Markdown
        #md = Markdown(extensions=['footnotes'], safe_mode=True)
        #self.html = md.convert(self.text)
        if not self.slug:
            self.slug = slugify(self.title)[:self._meta.get_field_by_name('slug')[0].max_length]
        super(Torrent, self).save(**kwargs)

Example 17

Project: wger
Source File: models.py
View license
    def get_absolute_url(self):
        '''
        Returns the canonical URL to view this object
        '''
        return reverse('nutrition:ingredient:view',
                       kwargs={'id': self.id, 'slug': slugify(self.name)})

Example 18

Project: wq.db
Source File: models.py
View license
def find_unique_slug(name, queryset):
    if not name:
        maxobj = queryset.order_by('-pk').first()
        name = str(maxobj.pk + 1 if maxobj else 1)
    if len(name) > 45:
        name = name[:45]
    slug = slugify(name)
    exists = queryset.filter(slug=slug)
    num = ''
    while exists.count() > 0:
        slug = slugify('%s %s' % (name, num))
        exists = queryset.filter(slug=slug)
        if num == '':
            num = 1
        else:
            num += 1
    return slug

Example 19

Project: django-hyperadmin
Source File: resources.py
View license
    def get_resource_slug(self):
        """
        Return the slug of this resource.
        Provides the return value of the `resource_slug` property.
        """
        if hasattr(self, '_resource_slug'):
            return self._resource_slug
        return slugify(self.get_resource_name())

Example 20

Project: django-event-rsvp
Source File: models.py
View license
    def save(self, *args, **kwargs):
        self.slug = slugify(self.title)
        suspects = Event.objects.filter(slug=self.slug)
        if suspects.count() > 0 and suspects[0] != self:
            while Event.objects.filter(slug=self.slug).count() > 0:
                try:
                    number = int(self.slug[-1])
                except ValueError:
                    self.slug = self.slug + '0'
                else:
                    self.slug = self.slug[:-1] + str(number + 1)
        super(Event, self).save(*args, **kwargs)

Example 21

Project: teerace
Source File: models.py
View license
	def slugify_title(self):
		new_slug = slug = slugify(self.title) or "bad-title"
		# preventing slugs from being non-unique, wordpress-style
		n = 1
		while True:
			try:
				slug_dupe = Entry.objects.get(slug=new_slug)
			except Entry.DoesNotExist:
				break
			n += 1
			if n != 1:
				new_slug = "{0}-{1}".format(slug, n)
		return new_slug

Example 22

Project: dj-dynamic-forms
Source File: models.py
View license
    def save(self, *args, **kwargs):
        if not self.name:
            self.name = slugify(self.label)

        given_options = self.options
        field_type_cls = dynamic_form_field_registry.get(self.field_type)
        invalid = set(self.options.keys()) - set(field_type_cls._meta.keys())
        if invalid:
            for key in invalid:
                del given_options[key]
            self.options = given_options

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

Example 23

Project: django-tumblelog
Source File: feeds.py
View license
    def item_description(self, item):
        return render_to_string(item.fields.rss_template, {
            'post': item,
            'obj': item,
            'post_type': slugify(item.fields.__class__.__name__),
            'list_view': False,
            'detail_view': True,
        })

Example 24

Project: avos
Source File: views.py
View license
    def get(self, request, keypair_name=None, optional=None):
        try:
            if optional == "regenerate":
                api.nova.keypair_delete(request, keypair_name)

            keypair = api.nova.keypair_create(request, keypair_name)
        except Exception:
            redirect = reverse('horizon:project:access_and_security:index')
            exceptions.handle(self.request,
                              _('Unable to create key pair: %(exc)s'),
                              redirect=redirect)

        response = http.HttpResponse(content_type='application/binary')
        response['Content-Disposition'] = ('attachment; filename=%s.pem'
                                           % slugify(keypair.name))
        response.write(keypair.private_key)
        response['Content-Length'] = str(len(response.content))
        return response

Example 25

Project: django-baseboard
Source File: models.py
View license
    def save(self, force_insert=False, force_update=False):
        if not self.basecamp_id:
            self.basecamp_id = Project.extract_basecamp_id(self.basecamp_url)
        
        self.detect_name()

        if not self.slug:
            self.slug = slugify("%s-%s" % (self.basecamp_id, self.name))

        self.updated_at = datetime.datetime.now()
        if not self.id:
            self.created_at = datetime.datetime.now()

        if not self.summary_data: self.update_summary()
        super(Project, self).save(force_insert, force_update)

Example 26

Project: coding-events
Source File: events.py
View license
    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title) or 'event'

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

        try:
            for tag in self.tag:
                self.tags.add(tag)
            for entry in self.audiencelist:
                self.audience.add(entry)
            for entry in self.themelist:
                self.theme.add(entry)
        except AttributeError:
            pass

Example 27

Project: django-articles
Source File: models.py
View license
    def do_unique_slug(self, using=DEFAULT_DB):
        """
        Ensures that the slug is always unique for the year this article was
        posted
        """

        if not self.id:
            # make sure we have a slug first
            if not len(self.slug.strip()):
                self.slug = slugify(self.title)

            self.slug = self.get_unique_slug(self.slug, using)
            return True

        return False

Example 28

Project: django-dilla
Source File: spammers.py
View license
@spam.global_handler('EmailField')
def random_email(record, field):
    return "%[email protected]%s.%s" % ( \
             slugify(_random_words(1)),
             slugify(_random_words(1)),
             random.choice(["com", "org", "net", "gov", "eu"])
             )

Example 29

Project: crate-site
Source File: models.py
View license
    def save(self, *args, **kwargs):
        if not self.name:
            raise  IntegrityError("Name cannot be empty")

        if not self.slug:
            slug = slugify(self.name)
            i = 1

            while List.objects.filter(user=self.user, slug=slug).exists():
                slug = slugify(u"%s %s" % (self.name, i))
                i += 1

            self.slug = slug

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

Example 30

Project: Dinette
Source File: models.py
View license
    def save(self, *args, **kwargs):
        if not self.slug:
            slug = slugify(self.user.username)
            if slug:
                same_slug_count = self._default_manager.filter(slug__startswith=slug).count()
                if same_slug_count:
                    slug = slug + str(same_slug_count)
                self.slug = slug
            else:
                #fallback to user id
                slug = self.user.id
        super(DinetteUserProfile, self).save(*args, **kwargs)

Example 31

Project: django-cms
Source File: api.py
View license
def generate_valid_slug(source, parent, language):
    """
    Generate a valid slug for a page from source for the given language.
    Parent is passed so we can make sure the slug is unique for this level in
    the page tree.
    """
    if parent:
        qs = Title.objects.filter(language=language, page__parent=parent)
    else:
        qs = Title.objects.filter(language=language, page__parent__isnull=True)
    used = list(qs.values_list('slug', flat=True))
    baseslug = slugify(source)
    slug = baseslug
    i = 1
    if used:
        while slug in used:
            slug = '%s-%s' % (baseslug, i)
            i += 1
    return slug

Example 32

Project: django-filer
Source File: files.py
View license
def get_valid_filename(s):
    """
    like the regular get_valid_filename, but also slugifies away
    umlauts and stuff.
    """
    s = get_valid_filename_django(s)
    filename, ext = os.path.splitext(s)
    filename = slugify(filename)
    ext = slugify(ext)
    if ext:
        return "%s.%s" % (filename, ext)
    else:
        return "%s" % (filename,)

Example 33

Project: django-crispy-forms
Source File: bootstrap.py
View license
    def __init__(self, name, *fields, **kwargs):
        super(Container, self).__init__(*fields, **kwargs)
        self.template = kwargs.pop('template', self.template)
        self.name = name
        self._active_originally_included = "active" in kwargs
        self.active = kwargs.pop("active", False)
        if not self.css_id:
            self.css_id = slugify(self.name)

Example 34

Project: 2buntu-blog
Source File: models.py
View license
    @models.permalink
    def get_absolute_url(self):
        kwargs, slug = {'id': self.id}, slugify(self.title)
        if slug:
            kwargs['slug'] = slug
        return ('articles:view', (), kwargs)

Example 35

Project: drawquest-web
Source File: models.py
View license
    def get_share_page_url(self, absolute=False):
        slug = slugify(self.title)

        if slug:
            url = reverse('quest', args=[util.base36encode(self.id), slug])
        else:
            url = '/q/{}'.format(util.base36encode(self.id))

        if absolute:
            url = 'http://' + settings.DOMAIN + url

        return url

Example 36

Project: django-any-urlfield
Source File: widgets.py
View license
    def format_output(self, rendered_widgets):
        """
        Custom rendering of the widgets.
        """
        urltypes = list(self.url_type_registry)
        url_type_html = rendered_widgets.pop(0)
        output = [url_type_html]

        # Wrap remaining options in <p> for scripting.
        for i, widget_html in enumerate(rendered_widgets):
            prefix = slugify(urltypes[i].prefix)  # can use [i], same order of adding items.
            output.append(u'<p class="any_urlfield-url-{0}" style="clear:left">{1}</p>'.format(prefix, widget_html))

        return u'<div class="related-widget-wrapper">{0}</div>'.format(u''.join(output))

Example 37

Project: edx-platform
Source File: course_complete.py
View license
def course_slug(course_key, mode):
    """
    Legacy: Not to be used as a model for constructing badge slugs. Included for compatibility with the original badge
    type, awarded on course completion.

    Slug ought to be deterministic and limited in size so it's not too big for Badgr.

    Badgr's max slug length is 255.
    """
    # Seven digits should be enough to realistically avoid collisions. That's what git services use.
    digest = hashlib.sha256(u"{}{}".format(unicode(course_key), unicode(mode))).hexdigest()[:7]
    base_slug = slugify(unicode(course_key) + u'_{}_'.format(mode))[:248]
    return base_slug + digest

Example 38

Project: feincms-elephantblog
Source File: factories.py
View license
def create_category(title):
    category = CategoryFactory.create()
    CategoryTranslationFactory.create(
        parent=category,
        title=title,
        slug=slugify(title)
    )
    return category

Example 39

Project: zipfelchappe
Source File: models.py
View license
    def get_choices(self):
        get_tuple = lambda val: (slugify(val.strip()), val.strip())
        choices = [get_tuple(value) for value in self.choices.split(',')]
        if not self.is_required and self.type == 'select':
            choices = models.fields.BLANK_CHOICE_DASH + choices
        return tuple(choices)

Example 40

View license
    def test_product_adds_additional_categories(self):
        p = Product(
            name='Product 5',
            slug=slugify('Product 5'),
            active=True,
            unit_price=Decimal(random.randint(50, 1000)),
            main_category=Category.objects.get(slug='level1-second')
        )
        
        p.save()
        self.assertEqual(p.additional_categories.all()[0].slug, 'level1-second')

Example 41

Project: django-app-metrics
Source File: models.py
View license
    def save(self, *args, **kwargs):
        if not self.id and not self.slug:
            self.slug = slugify(self.name)
            i = 0
            while True:
                try:
                    with atomic():
                        return super(Metric, self).save(*args, **kwargs)
                except IntegrityError:
                    i += 1
                    self.slug = "%s_%d" % (self.slug, i)
        else:
            return super(Metric, self).save(*args, **kwargs)

Example 42

Project: django-pagebits
Source File: models.py
View license
    def save(self, *args, **kwargs):
        # Slugify if does not exist on first save
        if not self.pk and not self.slug:
            self.slug = slugify(self.name)

        self.modified = timezone.now()

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

Example 43

Project: django_twitter
Source File: models.py
View license
    def parse_all(self):
        parts = self.text.split()
        hashtag_counter = 0
        mention_counter = 0
        result = {"parsed_text": "", "hashtags": [], "mentions": []}
        for index, value in enumerate(parts):
            if value.startswith("#"):
                parts[index] = "{hashtag" + str(hashtag_counter) + "}"
                hashtag_counter += 1
                result[u'hashtags'].append(slugify(value))
            if value.startswith("@"):
                parts[index] = "{mention" + str(mention_counter) + "}"
                mention_counter += 1
                result[u'mentions'].append(slugify(value))
        result[u'parsed_text'] = " ".join(parts)
        return result

Example 44

Project: radpress
Source File: models.py
View license
    def save(self, **kwargs):
        reader = get_reader(markup=self.markup)
        content_body, metadata = reader(self.content).read()

        if not self.content_body:
            self.content_body = content_body

        if not self.slug:
            self.slug = slugify(self.title)

        if not kwargs.pop('skip_updated_at', False):
            self.updated_at = datetime.datetime.now()

        super(Entry, self).save(**kwargs)

Example 45

Project: django-avatar
Source File: utils.py
View license
def get_cache_key(user_or_username, size, prefix):
    """
    Returns a cache key consisten of a username and image size.
    """
    if isinstance(user_or_username, get_user_model()):
        user_or_username = get_username(user_or_username)
    key = six.u('%s_%s_%s') % (prefix, user_or_username, size)
    return six.u('%s_%s') % (slugify(key)[:100],
                             hashlib.md5(force_bytes(key)).hexdigest())

Example 46

Project: soclone
Source File: __init__.py
View license
def clean_question_title(form):
    """
    Ensures that Question titles don't conflict with URLs used to take
    particular actions on a Question.
    """
    if slugify(form.cleaned_data['title']) in RESERVED_TITLES:
        internets = random.choice([
            u'We have filters on Internets which make',
            u"I hear there's rumors on the, uh, Internets that"])
        raise forms.ValidationError(
            u'%s this title is invalid - please choose another.' % internets)
    return form.cleaned_data['title']

Example 47

Project: mootiro-maps
Source File: models.py
View license
    def save(self, *args, **kwargs):
        # TODO: validate grantee as either a Proposal, a Resource or
        #       an Organization
        # TODO: validate investor as either a User or an Organization
        self.slug = slugify(self.name)
        super(Investment, self).save(*args, **kwargs)

Example 48

Project: jellyroll
Source File: lastfm.py
View license
def _tags_for_url(url):
    tags = set()
    try:
        xml = utils.getxml(url)
    except HttpLib2Error, e:
        if e.code == 408:
            return ""
        else:
            raise
    except SyntaxError:
        return ""
    for t in xml.getiterator("tag"):
        count = utils.safeint(t.find("count").text)
        if count >= getattr(settings, 'LASTFM_TAG_USAGE_THRESHOLD', 15):
            tag = slugify(smart_unicode(t.find("name").text))
            tags.add(tag[:50])
    
    return tags

Example 49

Project: django-omblog
Source File: listeners.py
View license
def post_create_slug(sender, instance, **kwargs):
    """Create a slug on freshly created blog posts"""

    if instance.pk and instance.slug is not None:
            return

    slug = slugify(instance.title)
    try:
        sender.objects.exclude(pk__in=[instance.pk])\
            .get(slug=slug)
        # append random characters and be done with it
        random = generate_random()
        slug = '%s-%s' % (slug, random)
    except (AttributeError, sender.DoesNotExist):
        pass
    instance.slug = slug

Example 50

Project: django-river
Source File: 0004_data_fix.py
View license
def set_slug(apps, schema_editor):
    # We can't import the Person model directly as it may be a newer
    # version than this migration expects. We use the historical version.
    State = apps.get_model("river", "State")

    for s in State.objects.all():
        s.slug = slugify(s.label)
        s.save()