Python django.utils.text.Truncator() Examples

The following are 30 code examples of django.utils.text.Truncator(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.utils.text , or try the search function .
Example #1
Source File: widgets.py    From python2017 with MIT License 6 votes vote down vote up
def label_and_url_for_value(self, value):
        key = self.rel.get_related_field().name
        try:
            obj = self.rel.model._default_manager.using(self.db).get(**{key: value})
        except (ValueError, self.rel.model.DoesNotExist):
            return '', ''

        try:
            url = reverse(
                '%s:%s_%s_change' % (
                    self.admin_site.name,
                    obj._meta.app_label,
                    obj._meta.object_name.lower(),
                ),
                args=(obj.pk,)
            )
        except NoReverseMatch:
            url = ''  # Admin not registered for target model.

        return Truncator(obj).words(14, truncate='...'), url 
Example #2
Source File: widgets.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
def label_and_url_for_value(self, value):
        key = self.rel.get_related_field().name
        try:
            obj = self.rel.model._default_manager.using(self.db).get(**{key: value})
        except (ValueError, self.rel.model.DoesNotExist, ValidationError):
            return '', ''

        try:
            url = reverse(
                '%s:%s_%s_change' % (
                    self.admin_site.name,
                    obj._meta.app_label,
                    obj._meta.object_name.lower(),
                ),
                args=(obj.pk,)
            )
        except NoReverseMatch:
            url = ''  # Admin not registered for target model.

        return Truncator(obj).words(14, truncate='...'), url 
Example #3
Source File: widgets.py    From python with Apache License 2.0 6 votes vote down vote up
def label_and_url_for_value(self, value):
        key = self.rel.get_related_field().name
        try:
            obj = self.rel.model._default_manager.using(self.db).get(**{key: value})
        except (ValueError, self.rel.model.DoesNotExist):
            return '', ''

        try:
            url = reverse(
                '%s:%s_%s_change' % (
                    self.admin_site.name,
                    obj._meta.app_label,
                    obj._meta.object_name.lower(),
                ),
                args=(obj.pk,)
            )
        except NoReverseMatch:
            url = ''  # Admin not registered for target model.

        return Truncator(obj).words(14, truncate='...'), url 
Example #4
Source File: tasks.py    From karrot-backend with GNU Affero General Public License v3.0 6 votes vote down vote up
def notify_message_push_subscribers_with_language(message, subscriptions, language):
    conversation = message.conversation

    if not translation.check_for_language(language):
        language = 'en'

    with translation.override(language):
        message_title = get_message_title(message, language)

    if message.is_thread_reply():
        click_action = frontend_urls.thread_url(message.thread)
    else:
        click_action = frontend_urls.conversation_url(conversation, message.author)

    notify_subscribers_by_device(
        subscriptions,
        click_action=click_action,
        fcm_options={
            'message_title': message_title,
            'message_body': Truncator(message.content).chars(num=1000),
            # this causes each notification for a given conversation to replace previous notifications
            # fancier would be to make the new notifications show a summary not just the latest message
            'tag': 'conversation:{}'.format(conversation.id),
        }
    ) 
Example #5
Source File: markdown.py    From karrot-backend with GNU Affero General Public License v3.0 6 votes vote down vote up
def render(text, truncate_words=None):
    html = markdown.markdown(
        text,
        extensions=[
            EmojiExtension(emoji_index=twemoji),
            SuperFencesCodeExtension(),
            MagiclinkExtension(),
            DeleteSubExtension(subscript=False),
            Nl2BrExtension(),
        ]
    )
    markdown_attrs['img'].append('class')
    markdown_tags.append('pre')
    clean_html = bleach.clean(html, markdown_tags, markdown_attrs)

    if truncate_words:
        clean_html = Truncator(clean_html).words(num=truncate_words, html=True)

    return clean_html 
Example #6
Source File: widgets.py    From bioforum with MIT License 6 votes vote down vote up
def label_and_url_for_value(self, value):
        key = self.rel.get_related_field().name
        try:
            obj = self.rel.model._default_manager.using(self.db).get(**{key: value})
        except (ValueError, self.rel.model.DoesNotExist):
            return '', ''

        try:
            url = reverse(
                '%s:%s_%s_change' % (
                    self.admin_site.name,
                    obj._meta.app_label,
                    obj._meta.object_name.lower(),
                ),
                args=(obj.pk,)
            )
        except NoReverseMatch:
            url = ''  # Admin not registered for target model.

        return Truncator(obj).words(14, truncate='...'), url 
Example #7
Source File: relfield.py    From imoocc with GNU General Public License v2.0 5 votes vote down vote up
def label_for_value(self, value):
        key = self.rel.get_related_field().name
        try:
            obj = self.rel.to._default_manager.using(
                self.db).get(**{key: value})
            return '%s' % escape(Truncator(obj).words(14, truncate='...'))
        except (ValueError, self.rel.to.DoesNotExist):
            return "" 
Example #8
Source File: utils.py    From django-userena-ce with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def truncate_words(s, num, end_text="..."):
    truncate = end_text and " %s" % end_text or ""
    return Truncator(s).words(num, truncate=truncate) 
Example #9
Source File: filters.py    From devops with MIT License 5 votes vote down vote up
def label_for_value(self, other_model, rel_name, value):
        try:
            obj = other_model._default_manager.get(**{rel_name: value})
            return '%s' % escape(Truncator(obj).words(14, truncate='...'))
        except (ValueError, other_model.DoesNotExist):
            return "" 
Example #10
Source File: relfield.py    From devops with MIT License 5 votes vote down vote up
def label_for_value(self, value):
        key = self.rel.get_related_field().name
        try:
            obj = self.rel.to._default_manager.using(
                self.db).get(**{key: value})
            return '%s' % escape(Truncator(obj).words(14, truncate='...'))
        except (ValueError, self.rel.to.DoesNotExist):
            return "" 
Example #11
Source File: rss.py    From foundation.mozilla.org with Mozilla Public License 2.0 5 votes vote down vote up
def item_description(self, item):
        page = item.specific
        html = str(page.body)
        text = Truncator(html).chars(1000, html=True)
        return text 
Example #12
Source File: filters.py    From online with GNU Affero General Public License v3.0 5 votes vote down vote up
def label_for_value(self, other_model, rel_name, value):
        try:
            obj = other_model._default_manager.get(**{rel_name: value})
            return '%s' % escape(Truncator(obj).words(14, truncate='...'))
        except (ValueError, other_model.DoesNotExist):
            return "" 
Example #13
Source File: relfield.py    From online with GNU Affero General Public License v3.0 5 votes vote down vote up
def label_for_value(self, value):
        key = self.rel.get_related_field().name
        try:
            obj = self.rel.to._default_manager.using(
                self.db).get(**{key: value})
            return '%s' % escape(Truncator(obj).words(14, truncate='...'))
        except (ValueError, self.rel.to.DoesNotExist):
            return "" 
Example #14
Source File: filters.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def label_for_value(self, other_model, rel_name, value):
        try:
            obj = other_model._default_manager.get(**{rel_name: value})
            return '%s' % escape(Truncator(obj).words(14, truncate='...'))
        except (ValueError, other_model.DoesNotExist):
            return "" 
Example #15
Source File: relfield.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def label_for_value(self, value):
        key = self.rel.get_related_field().name
        try:
            obj = self.rel.to._default_manager.using(
                self.db).get(**{key: value})
            return '%s' % escape(Truncator(obj).words(14, truncate='...'))
        except (ValueError, self.rel.to.DoesNotExist):
            return "" 
Example #16
Source File: filters.py    From imoocc with GNU General Public License v2.0 5 votes vote down vote up
def label_for_value(self, other_model, rel_name, value):
        try:
            obj = other_model._default_manager.get(**{rel_name: value})
            return '%s' % escape(Truncator(obj).words(14, truncate='...'))
        except (ValueError, other_model.DoesNotExist):
            return "" 
Example #17
Source File: test_text.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_truncate_chars(self):
        truncator = text.Truncator('The quick brown fox jumped over the lazy dog.')
        self.assertEqual('The quick brown fox jumped over the lazy dog.', truncator.chars(100)),
        self.assertEqual('The quick brown fox ...', truncator.chars(23)),
        self.assertEqual('The quick brown fo.....', truncator.chars(23, '.....')),

        nfc = text.Truncator('o\xfco\xfco\xfco\xfc')
        nfd = text.Truncator('ou\u0308ou\u0308ou\u0308ou\u0308')
        self.assertEqual('oüoüoüoü', nfc.chars(8))
        self.assertEqual('oüoüoüoü', nfd.chars(8))
        self.assertEqual('oü...', nfc.chars(5))
        self.assertEqual('oü...', nfd.chars(5))

        # Ensure the final length is calculated correctly when there are
        # combining characters with no precomposed form, and that combining
        # characters are not split up.
        truncator = text.Truncator('-B\u030AB\u030A----8')
        self.assertEqual('-B\u030A...', truncator.chars(5))
        self.assertEqual('-B\u030AB\u030A-...', truncator.chars(7))
        self.assertEqual('-B\u030AB\u030A----8', truncator.chars(8))

        # Ensure the length of the end text is correctly calculated when it
        # contains combining characters with no precomposed form.
        truncator = text.Truncator('-----')
        self.assertEqual('---B\u030A', truncator.chars(4, 'B\u030A'))
        self.assertEqual('-----', truncator.chars(5, 'B\u030A'))

        # Make a best effort to shorten to the desired length, but requesting
        # a length shorter than the ellipsis shouldn't break
        self.assertEqual('...', text.Truncator('asdf').chars(1))
        # lazy strings are handled correctly
        self.assertEqual(text.Truncator(lazystr('The quick brown fox')).chars(12), 'The quick...') 
Example #18
Source File: test_text.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_truncate_chars(self):
        truncator = text.Truncator('The quick brown fox jumped over the lazy dog.')
        self.assertEqual('The quick brown fox jumped over the lazy dog.', truncator.chars(100)),
        self.assertEqual('The quick brown fox …', truncator.chars(21)),
        self.assertEqual('The quick brown fo.....', truncator.chars(23, '.....')),

        nfc = text.Truncator('o\xfco\xfco\xfco\xfc')
        nfd = text.Truncator('ou\u0308ou\u0308ou\u0308ou\u0308')
        self.assertEqual('oüoüoüoü', nfc.chars(8))
        self.assertEqual('oüoüoüoü', nfd.chars(8))
        self.assertEqual('oü…', nfc.chars(3))
        self.assertEqual('oü…', nfd.chars(3))

        # Ensure the final length is calculated correctly when there are
        # combining characters with no precomposed form, and that combining
        # characters are not split up.
        truncator = text.Truncator('-B\u030AB\u030A----8')
        self.assertEqual('-B\u030A…', truncator.chars(3))
        self.assertEqual('-B\u030AB\u030A-…', truncator.chars(5))
        self.assertEqual('-B\u030AB\u030A----8', truncator.chars(8))

        # Ensure the length of the end text is correctly calculated when it
        # contains combining characters with no precomposed form.
        truncator = text.Truncator('-----')
        self.assertEqual('---B\u030A', truncator.chars(4, 'B\u030A'))
        self.assertEqual('-----', truncator.chars(5, 'B\u030A'))

        # Make a best effort to shorten to the desired length, but requesting
        # a length shorter than the ellipsis shouldn't break
        self.assertEqual('…', text.Truncator('asdf').chars(0))
        # lazy strings are handled correctly
        self.assertEqual(text.Truncator(lazystr('The quick brown fox')).chars(10), 'The quick…') 
Example #19
Source File: test_text.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_truncate_words(self):
        truncator = text.Truncator('The quick brown fox jumped over the lazy dog.')
        self.assertEqual('The quick brown fox jumped over the lazy dog.', truncator.words(10))
        self.assertEqual('The quick brown fox...', truncator.words(4))
        self.assertEqual('The quick brown fox[snip]', truncator.words(4, '[snip]'))
        # lazy strings are handled correctly
        truncator = text.Truncator(lazystr('The quick brown fox jumped over the lazy dog.'))
        self.assertEqual('The quick brown fox...', truncator.words(4)) 
Example #20
Source File: widgets.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def label_for_value(self, value):
        key = self.rel.get_related_field().name
        try:
            obj = self.rel.model._default_manager.using(self.db).get(**{key: value})
            return '&nbsp;<strong>%s</strong>' % escape(Truncator(obj).words(14, truncate='...'))
        except (ValueError, self.rel.model.DoesNotExist):
            return '' 
Example #21
Source File: test_text.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_truncate_words(self):
        truncator = text.Truncator('The quick brown fox jumped over the lazy dog.')
        self.assertEqual('The quick brown fox jumped over the lazy dog.', truncator.words(10))
        self.assertEqual('The quick brown fox…', truncator.words(4))
        self.assertEqual('The quick brown fox[snip]', truncator.words(4, '[snip]'))
        # lazy strings are handled correctly
        truncator = text.Truncator(lazystr('The quick brown fox jumped over the lazy dog.'))
        self.assertEqual('The quick brown fox…', truncator.words(4)) 
Example #22
Source File: models.py    From django-beginners-guide with MIT License 5 votes vote down vote up
def __str__(self):
        truncated_message = Truncator(self.message)
        return truncated_message.chars(30) 
Example #23
Source File: filters.py    From ImitationTmall_Django with GNU General Public License v3.0 5 votes vote down vote up
def label_for_value(self, other_model, rel_name, value):
        try:
            obj = other_model._default_manager.get(**{rel_name: value})
            return '%s' % escape(Truncator(obj).words(14, truncate='...'))
        except (ValueError, other_model.DoesNotExist):
            return "" 
Example #24
Source File: relfield.py    From ImitationTmall_Django with GNU General Public License v3.0 5 votes vote down vote up
def label_for_value(self, value):
        key = self.rel.get_related_field().name
        try:
            obj = self.rel.to._default_manager.using(
                self.db).get(**{key: value})
            return '%s' % escape(Truncator(obj).words(14, truncate='...'))
        except (ValueError, self.rel.to.DoesNotExist):
            return "" 
Example #25
Source File: server.py    From esdc-ce with Apache License 2.0 5 votes vote down vote up
def log_name(self):  # Required by task_log
        return Truncator(self.uri).chars(32) 
Example #26
Source File: imagestore.py    From esdc-ce with Apache License 2.0 5 votes vote down vote up
def log_name(self):  # Required by task_log
        return Truncator(self.url).chars(32) 
Example #27
Source File: admin.py    From youtube-audio-dl with MIT License 5 votes vote down vote up
def video_title(self, obj):
        return Truncator(obj.video.title).chars(50) 
Example #28
Source File: models.py    From srvup-membership with MIT License 5 votes vote down vote up
def get_preview(self):
		#return truncatechars(self.text, 120)
		return Truncator(self.text).chars(120) 
Example #29
Source File: fields.py    From steemprojects.com with MIT License 5 votes vote down vote up
def clean(self, value):
        value = value and Truncator(value).chars(self.max_length, truncate='...')

        return super(TruncatingCharField, self).clean(value) 
Example #30
Source File: serializers.py    From coding-events with MIT License 5 votes vote down vote up
def transform_description_short(self, obj, value):
        return Truncator(value).chars(160)