How to add post/content reading time in a django blog?

流过昼夜 提交于 2019-12-12 04:27:19

问题


I am trying to add content read time in django app (posts) but its not working properly don't know whats going wrong.

posts/models.py :

from django.db import models
from django.core.urlresolvers import reverse
from django.conf import settings
from django.db.models.signals import pre_save
from django.utils import timezone
from markdown_deux import markdown
from django.utils.safestring import mark_safe
from .utils import get_read_time

#from comments.models import Comment
#from django.contrib.contenttypes.models import ContentType


#to specify image upload location we define a function

#def upload_location(instance, filename):
   # return "%s/%s" % (instance.pk, filename)

class PostManager(models.Manager):
    def active(self, *args, **kwargs):
        return super(PostManager,self).filter(draft=False).filter(publish__lte=timezone.now())


class Post(object):
    pass


class Post(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
    title = models.CharField(max_length=120)
    image = models.ImageField(null=True,
                              blank=True,)
                              #upload_to=upload_location)

    content = models.TextField()
    draft = models.BooleanField(default=False)
    publish = models.DateField(auto_now=False, auto_now_add=False)
    read_time = models.IntegerField(default=0)
    updated = models.DateTimeField(auto_now=True, auto_now_add=False)
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)


    objects = PostManager()
    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('detail', kwargs={'pk': self.pk})


    # for latest posts on top of page
    class Meta:
        ordering = ['-timestamp', 'updated']

    def get_markdown(self):
        content = self.content
        markdown_text = markdown(content)
        return mark_safe(markdown_text)

   # @property
    #def comments(self):
    #    instance = self
    #    qs = Comment.objects.filter_by_instance(instance)
    #    return qs

   # @property
    #def get_content_type(self):
    #    instance = self
    #    content_type = ContentType.objects.get_for_models(instance.__class__)
    #    return content_type

    def pre_save_post_receiver(sender, instance, *args, **kwargs):
        if instance.content:
            html_string = instance.get_markdown()
            read_time_var = get_read_time(html_string)
            instance.read_time = read_time_var

    pre_save.connect(pre_save_post_receiver, sender=Post)

Added a python file in my app as utils.py

posts/utils.py

import datetime
import re
import math
from django.utils.html import strip_tags

def count_words(html_string):
    word_string = strip_tags(html_string)
    matching_words = re.findall(r'\w+', word_string)
    count = len(matching_words)
    return count

def get_read_time(html_string):
    count = count_words(html_string)
    #read_time_min = (count/200.0)
    read_time_min = math.ceil(count/200.0)
    #read_time_sec = read_time_min * 60
    #read_time = str(datetime.timedelta(seconds=read_time_sec))
    read_time = str(datetime.timedelta(minutes=read_time_min))
    return int(read_time)

code from posts/posts_detail.html:

<div class="col-sm-6 col-sm-offset-3">
        {% if instance.image %}
            <img src="{{ instance.image.url }}" class="img-responsive">
        {% endif %}
        <h1>{{ title }} <small>
            {% if instance.draft %}
                <span style="color: red"> (Draft) </span>
            {% endif %}
            {{ instance.publish}}</small></h1>
        <p>Read time: {% if instance.read_time <= 1 %} < 1 Minute {% else %}{{ instance.read_time }} minutes {% endif %}</p>
        {% if instance.user.get_full_name %}
            <p>Author : {{ instance.user.get_full_name }}</p>
        {% endif %}

I am getting Read time: 0 in admin and Read time: < 1 Minute in blog

Don't know where making mistake.

Please Guide.

Note: Using Django 1.10 and Python 3.4

来源:https://stackoverflow.com/questions/43762694/how-to-add-post-content-reading-time-in-a-django-blog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!