简体   繁体   English

如何创建一个 Django model function 来返回博客帖子的读取时间,如果正文有 ZFC365FDC70D5267D

[英]How to create a Django model function that returns the read time of a blog Post, if the body has html tags in it?

I'm creating a Django Blog, and I saw the feature of average read time in blogs like medium or dev.to and I ask myself how can implement it.我正在创建一个 Django 博客,我在 medium 或 dev.to 等博客中看到了平均阅读时间的特性,我问自己如何实现它。

blog/models.py:博客/models.py:

class Post(models.Model):
    title = models.CharField(max_length=200)
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    header_image = models.ImageField(blank=True, null=True, upload_to="images/post_header/")
    date = models.DateField(auto_now_add=True) 
    description = models.TextField(blank=True, null=True)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    # body = models.TextField()
    body = RichTextField()
    upvotes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="post_votes")
    
    def total_likes(self):
        """
        Returns total likes in the page
        """
        return self.upvotes.count()

    def __str__(self):
        """
        Show the title and the author in the admin Page
        """
        return self.title + " by " + str(self.author)
    
    def get_time_read(self):
        return "Some tricky code to get the body of the post and return the words stripping the 
                                                                                           tags"



    def get_absolute_url(self):
        return reverse("blog:article_page", kwargs={"pk": self.pk})

I think that the easiest way is to implement a function in the Post model, that returns the read time of an average adult person, by counting the total words and dividing it by the average words per minute (aprox 200 w/m), and after that pass the function to the html template and render the time read.我认为最简单的方法是在 Post model 中实现 function,通过计算总字数并将其除以每分钟的平均字数(大约 200 w/m),返回普通成年人的阅读时间,以及之后将 function 传递给 html 模板并渲染时间读取。

That would be easy of implement, If there weren't html tags in the blog Post body, since I use a Rich Text Editor (django-ckeditor) in the form to write it.这将很容易实现,如果博客文章正文中没有html标记,因为我在表单中使用富文本编辑器(django-ckeditor)来编写它。

So how can I get the content of the blog post body and how can I strip the tags to get the total words?那么如何获取博客文章正文的内容以及如何剥离标签以获取总字数?

One way would be to use a library such as beautiful soup to parse your html.一种方法是使用诸如美丽汤之类的库来解析您的 html。 Then you can just count the words:然后你可以数单词:

from bs4 import BeautifulSoup

WORDS_PER_MINUTE = 100

class Post(models.Model):
    ...
    def get_reading_time(self):
        soup = BeautifulSoup(self.body, 'html.parser')
        text = soup.get_text()
        word_count = len(text.split())
        read_time = word_count / WORDS_PER_MINUTE
        return read_time

For what it's worth.物有所值。 This isn't necessarily how I would do this:这不一定是我会这样做:

Imagine you're writing a blog about how to use django.想象一下,您正在写一篇关于如何使用 django 的博客。 You'll have sections in there which are code.您将在其中包含代码部分。 How long does it take you to read code?阅读代码需要多长时间? It depends on the code and how long you have to think about it.这取决于代码以及您需要考虑多长时间。 Likewise for any subject, some blogs just take longer to read irrespective of word-count.同样对于任何主题,有些博客的阅读时间更长,与字数无关。

One way might be just to add read time as a required field, and ask the blog-post author to provide an estimated read time.一种方法可能只是将阅读时间添加为必填字段,并要求博客文章作者提供估计的阅读时间。 There are of course disadvantages with that approach too though.当然,这种方法也有缺点。 If you have lots of authors, with different reading speeds you'll have inconsistent estimates across your site.如果您有很多作者,并且阅读速度不同,那么您整个网站的估计值就会不一致。

Something to think about...有什么要考虑的...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 django2.1 中创建博客 mdel,这样我就不需要使用标签<p> ,<h3> ,还有,每次写博客都要加html标签 - How do I create a Blog mdel in django2.1, So that I don't need to use tags <p>,<h3>,<b> and all, Each time write blog I have to add html tags 当嵌套序列化程序中有另一个模型(manytomany)时,我如何在 django 模型上发布,我想同时创建两者 - How do I post on a django model when it has another model (manytomany ) inside nested serializers, I want at the same time to create both 没有HTML输出到Django的博客文章 - No HTML output to blog post with Django 如何在 django 博客中添加帖子/内容阅读时间? - How to add post/content reading time in a django blog? html 如何在 django 中格式化我的博客文章? - How do I html format my blog post in django? Django-如何按常用标签列出博客项目 - Django - How to list blog items by their common tags 如何使用 Django 创建视频博客? - How to create a video blog with Django? 如何读取/编辑具有html标记的.txt文件 - How to read/edit a .txt file that has html tags 如何在 HTML 音频源标签中链接 Django 模型的属性? - How to link a Django model's property in HTML audio source tags? 如何使用Django博客撰写复杂的帖子 - How to make complex post with Django blog
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM