如何在django博客中添加帖子/内容阅读时间?

时间:2017-05-03 14:19:52

标签: python django web-applications django-models blogs

我正在尝试在django应用中添加内容阅读时间(帖子),但它无法正常工作,不知道哪里出错了。

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)

在我的应用中添加了一个python文件 utils.py

文章/ 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)

代码来自 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 %}

我在Read time: 0admin博客中获得Read time: < 1 Minute

不知道哪里犯了错误。

请指南。

注意:使用Django 1.10和Python 3.4

2 个答案:

答案 0 :(得分:1)

如果您打算使用 python readtime 库,还有另一种方法。它非常简单且易于集成。

pip install readtime

然后你必须将它导入到models.py文件中(这里是Post Model):

import readtime 

在模型中添加一个函数。

class Post(models.Model):
   user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
   title = models.CharField(max_length=120)
   content = models.TextField()

   def get_readtime(self):
      result = readtime.of_text(self.content)
      return result.text 

   def __str__(self):
      return self.title

如果你的views.py是这样的:

 def post_detail(request, id):
       post_detail = get_object_or_404(Post, id=id)
       context = {
          'post_detail':post_detail,
           }
       return render(request, 'post/post_detail.html', context)

然后在帖子详细信息模板中使用:

 {{post_detail.get_readtime}}
  

答案 1 :(得分:0)

read_time = models.IntegerField(default=0)

我认为你应该使用 TimeField 而不是 IntegerField

read_time = models.TimeField(null=True, blank=True)