【问题标题】:How to add post/content reading time in a django blog?如何在 django 博客中添加帖子/内容阅读时间?
【发布时间】:2017-10-01 10:35:47
【问题描述】:

我正在尝试在 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

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)

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

我在admin 中收到Read time: 0,在博客中收到Read time: &lt; 1 Minute

不知道哪里出错了。

请指导。

注意:使用 Django 1.10 和 Python 3.4

【问题讨论】:

  • @e4c5 你能帮帮我吗!?
  • instance.read_time??但是你注册的函数名是get_read_time。不一样吗?你能发布管理代码和显示的内容吗?

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


【解决方案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}}
  

【讨论】:

    【解决方案2】:
    read_time = models.IntegerField(default=0)
    

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

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

    【讨论】:

      猜你喜欢
      • 2014-06-02
      • 1970-01-01
      • 2016-03-25
      • 1970-01-01
      • 1970-01-01
      • 2020-10-06
      • 1970-01-01
      • 1970-01-01
      • 2023-02-22
      相关资源
      最近更新 更多