File tree Expand file tree Collapse file tree 2 files changed +20
-1
lines changed Expand file tree Collapse file tree 2 files changed +20
-1
lines changed Original file line number Diff line number Diff line change
1
+ import markdown
2
+
1
3
from django .db import models
2
4
from django .contrib .auth .models import User
3
5
from django .urls import reverse
4
6
from django .utils .six import python_2_unicode_compatible
7
+ from django .utils .html import strip_tags
5
8
6
9
7
10
# python_2_unicode_compatible 装饰器用于兼容 Python2
@@ -88,3 +91,19 @@ class Meta:
88
91
def increase_views (self ):
89
92
self .views += 1
90
93
self .save (update_fields = ['views' ])
94
+
95
+ def save (self , * args , ** kwargs ):
96
+ # 如果没有填写摘要
97
+ if not self .excerpt :
98
+ # 首先实例化一个 Markdown 类,用于渲染 body 的文本
99
+ md = markdown .Markdown (extensions = [
100
+ 'markdown.extensions.extra' ,
101
+ 'markdown.extensions.codehilite' ,
102
+ ])
103
+ # 先将 Markdown 文本渲染成 HTML 文本
104
+ # strip_tags 去掉 HTML 文本的全部 HTML 标签
105
+ # 从文本摘取前 54 个字符赋给 excerpt
106
+ self .excerpt = strip_tags (md .convert (self .body ))[:54 ]
107
+
108
+ # 调用父类的 save 方法将数据保存到数据库中
109
+ super (Post , self ).save (* args , ** kwargs )
Original file line number Diff line number Diff line change @@ -19,7 +19,7 @@ <h1 class="entry-title">
19
19
</ div >
20
20
</ header >
21
21
< div class ="entry-content clearfix ">
22
- < p > {{ post.excerpt }}</ p >
22
+ < p > {{ post.excerpt }}... </ p >
23
23
< div class ="read-more cl-effect-14 ">
24
24
< a href ="{{ post.get_absolute_url }} " class ="more-link "> 继续阅读 < span class ="meta-nav "> →</ span > </ a >
25
25
</ div >
You can’t perform that action at this time.
0 commit comments