def post_loop(max_posts):
    posts = Post.objects.filter(
        status__title="Published").order_by('-post_date')[:max_posts]

    output = ""

    for x in range(0, len(posts)):
        post = posts[x]
        permalink = functions.permalink(post.category.slug, post.slug)
        summary = Truncator(post.content_html)
        properties = {
            'TITLE': post.title,
            'TITLE_LINK': functions.make_link(permalink, post.title),
            'PERMALINK': permalink,
            'BODY': mark_safe(summary.words(100, html=True)),
            'CATEGORY': post.category,
            'POST_DATE': post.post_date,
            'CREATED_DATE': post.created,
            'LAST_EDIT_DATE': post.last_edited,
            'AUTHOR': post.author,
            'LAST_EDITOR': post.last_editor,
        }
        output += render_to_string(
            functions.get_template_file_path("postloop"), properties)

    return output
def post_loop(max_posts):
    posts = Post.objects.filter(
        status__title="Published").order_by('-post_date')[:max_posts]

    output = ""

    for x in range(0, len(posts)):
        post = posts[x]
        permalink = functions.permalink(post.category.slug, post.slug)
        summary = Truncator(post.content_html)
        properties = {
            'TITLE': post.title,
            'TITLE_LINK': functions.make_link(permalink, post.title),
            'PERMALINK': permalink,
            'BODY': mark_safe(summary.words(100, html=True)),
            'CATEGORY': post.category,
            'POST_DATE': post.post_date,
            'CREATED_DATE': post.created,
            'LAST_EDIT_DATE': post.last_edited,
            'AUTHOR': post.author,
            'LAST_EDITOR': post.last_editor,
        }
        output += render_to_string(
            functions.get_template_file_path("postloop"), properties)

    return output
Exemple #3
0
def find_post_content(feed_obj, entry):
    """Find the correct content field for a post."""
    try:
        content = entry["content"][0]["value"]
    except (IndexError, KeyError):
        content = entry.get("description") or entry.get("summary") or ""

    if '<img' not in content:
        # if there's no image and the we add an image to the feed
        def build_img(img_dict):
            try:
                # The tag is url instead of src... pain
                img = "<img src='%s'" % img_dict.get("url")
            except KeyError:
                return ''
            img_dict.pop('url')
            for attr in img_dict.items():
                img += "%s='%s'" % (attr[0], attr[1])
            img += ">"
            return img

        try:
            thumbnail = entry["media_thumbnail"][0]
            img = build_img(thumbnail)
        except (IndexError, KeyError):
            img = ""
        content = img + content
    try:
        truncator = Truncator(text=content)
        content =truncator.words(num=conf.DEFAULT_ENTRY_WORD_LIMIT, html=True)
    except UnicodeDecodeError:
        content = ""

    return feed_content_optimizer.optimize(content)
Exemple #4
0
def find_post_content(feed_obj, entry):
    """Find the correct content field for a post."""
    try:
        content = entry["content"][0]["value"]
    except (IndexError, KeyError):
        content = entry.get("description") or entry.get("summary") or ""

    if '<img' not in content:
        # if there's no image and the we add an image to the feed
        def build_img(img_dict):
            try:
                # The tag is url instead of src... pain
                img = "<img src='%s'" % img_dict.get("url")
            except KeyError:
                return ''
            img_dict.pop('url')
            for attr in img_dict.items():
                img += "%s='%s'" % (attr[0], attr[1])
            img += ">"
            return img

        try:
            thumbnail = entry["media_thumbnail"][0]
            img = build_img(thumbnail)
        except (IndexError, KeyError):
            img = ""
        content = img + content
    try:
        truncator = Truncator(text=content)
        content = truncator.words(num=conf.DEFAULT_ENTRY_WORD_LIMIT, html=True)
    except UnicodeDecodeError:
        content = ""

    return feed_content_optimizer.optimize(content)
Exemple #5
0
 def render(self, value):
     """Overload render to optionally truncate words."""
     value = super().render(value)
     if self.truncate_words is not None:
         trunc = Truncator(value)
         value = trunc.words(self.truncate_words)
     return value
Exemple #6
0
 def get_excerpt(self, max_words=55, end_text='...'):
     if not self.excerpt_html:
         truncator = Truncator(self.content_html)
         if end_text == '...':
             end_text = '&hellip;'
         return mark_safe(truncator.words(max_words, end_text, html=True))
     else:
         return mark_safe(self.excerpt_html)
Exemple #7
0
    def _get_teaser(self):
        """
        Retrieve some part of the article or the article's description.
        """
        if not self._teaser:
            if len(self.description.strip()):
                self._teaser = self.description
            else:
                truncator = Truncator(self.rendered_content)
                self._teaser = truncator.words(WORD_LIMIT, html=True)

        return self._teaser
Exemple #8
0
    def notify_question_author(answer):
        title_truncated = Truncator(answer.question.title)

        subject = "Новый ответ к вопросу {} - Hasker".format(
            title_truncated.words(5))
        message = """
            <p>Получен новый ответ от пользователя {answer_author}
            к вашему вопросу <a href="{q_url}">{q_title}</a>:</p>
            <p>{a_text}</p>
        """.format(answer_author=answer.author.username,
                   q_url=answer.question.url,
                   q_title=title_truncated.words(10),
                   a_text=Truncator(answer.text).words(25))
        from_email = settings.TECH_EMAIL
        recipient_list = [answer.author.email]

        send_mail(subject,
                  message,
                  from_email,
                  recipient_list,
                  fail_silently=True)
Exemple #9
0
    def get_excerpt(self, max_words=20, end_text='...'):
        content = self.get_content()
        if hasattr(content, '__html__'):
            # The __html__ attribute means the content was previously
            # marked as safe, so can include HTML tags.
            truncator = Truncator(content.__html__())
            if end_text == '...':
                end_text = '&hellip;'

            return mark_safe(truncator.words(max_words, end_text, html=True))
        else:
            return Truncator(content).words(max_words, end_text, html=False)
Exemple #10
0
 def avoid_truncated_word(self, text): 
     """Truncate in a way that text will be shorter than max_length and won't be cut in the middle of a word""" 
     words = text.split()
     if not words:
         return text
     truncator = Truncator(text)
     last_word = text.split()[-1]
     text = truncator.chars(self.max_length, '')
     truncated_last_word = text.split()[-1]
     if truncated_last_word !=  last_word: 
         # last word is cut. So, remove it
         num_words = len(text.split())
         text = truncator.words(num_words - 1) 
     return text
    def item_description(self, item):
        description = '<p>Election Date: <strong> %s </strong></p>' % (
            dateformat.format(item.date, 'N d, Y'))
        if item.registered_voters > 0:
            description += '<p>Registered Voters: <strong> %s </strong></p>' % (
                str(format(item.registered_voters, ',d')))
        if item.show_results and item.cast_votes > 0:
            description += '<p>Cast Votes: <strong> %s </strong></p>' % (str(
                format(item.cast_votes, ',d')))

        text = Truncator(item.description)
        description += text.words(30)

        return description
Exemple #12
0
    def get_meta_data(self, request):
        truncator = Truncator(strip_tags(self.content))
        description = truncator.words(35)
        image = ''

        full_domain = '{}://{}'.format(settings.META_SITE_PROTOCOL,
                                       settings.META_SITE_DOMAIN)

        if self.hero_image:
            thumbnail = get_thumbnail(self.hero_image,
                                      '900x350',
                                      crop='center')
            image = '{}{}'.format(full_domain, thumbnail.url)

        url = '{}{}'.format(full_domain, self.get_absolute_url())

        return {
            'type': 'article',
            'title': self.title,
            'description': description,
            'image': image,
            'url': url,
        }
Exemple #13
0
 def title(self):
     truncator = Truncator(self.topics)
     return truncator.words(12)
Exemple #14
0
 def __unicode__(self):
     if self.wrapper:
         text = Truncator(u'%s: %s' % (self.wrapper, strip_tags(self.body)))
     else:
         text = Truncator(strip_tags(self.body))
     return Truncator(text.words(7)).chars(38)
Exemple #15
0
 def label_for_value(self, value):
     key = self.rel.get_related_field().name
     obj = self.rel.to._default_manager.get(**{key: value})
     trunc = Truncator(obj)
     return trunc.words(obj, 14)
Exemple #16
0
 def item_description(self, item):
     truncator = Truncator(item.summary)
     return truncator.words(75, html=True)
Exemple #17
0
 def __unicode__(self):
     if self.wrapper:
         text = Truncator(u'%s: %s' % (self.wrapper, strip_tags(self.body)))
     else:
         text = Truncator(strip_tags(self.body))
     return Truncator(text.words(7)).chars(38)
Exemple #18
0
 def test_string_formatting(self):
     """ Test the human representation of a message """
     message = Message.objects.get(pk=1)
     truncated_body = Truncator.words(message.body, 10)
     self.failUnlessEqual(message.__unicode__(),
                          truncated_body)
Exemple #19
0
 def title(self):
     truncator = Truncator(self.topics)
     return truncator.words(12)
Exemple #20
0
 def get_short_description(self, obj):
     t = Truncator(obj.post)
     return t.words(30, html=True)
Exemple #21
0
 def item_description(self, item):
     truncator = Truncator(item.summary)
     return truncator.words(75, html=True)
Exemple #22
0
 def __unicode__(self):
     """ Human representation, displaying first ten words of the body. """
     truncator = Truncator(self.body)
     truncated_body = truncator.words(10)
     return "%(truncated_body)s" % {'truncated_body': truncated_body}
Exemple #23
0
def truncatehtml(string, length):
    truncator = Truncator(string)
    return truncator.words(length, html=True)
Exemple #24
0
 def label_for_value(self, value):
     key = self.rel.get_related_field().name
     obj = self.rel.to._default_manager.get(**{key: value})
     trunc = Truncator(obj)
     return trunc.words(obj, 14)