

从0到1搭建个人网站 七-在django模板中使用自定义属性
source link: http://www.lcsays.com/blogshow?blogId=133
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.


展示简单的文章标题
首先我们来把这样的标题《教你成为全栈工程师(Full Stack Developer) 十九-文章内容展示页面设计》去掉前面tag部分变成《十九-文章内容展示页面设计》,直接在模板里操作会比较复杂,这时我们来自定义一个get_simple_title的属性,修改web/models.py,为BlogPost类添加如下方法
def get_simple_title(self):
return self.title.replace(self.tags.first().name, '')
这时我们修改web/templates/web/blog_show.html如下:
{% for blog_post in tag.get_latest_blogpost.all %}
{% if forloop.counter < 5 %}
<a href="{% url 'blog_show' %}?blogId={{ blog_post.id }}">
{{ blog_post.get_simple_title }}
</a>
<br />
{% endif %}
{% endfor %}
这样便直接展示了去掉标签后的标题了
获取最新n篇文章
在首页分标签栏目中,我们要展示最新发布的5篇文章,这同样难以在模板中实现,因此我们自定义get_latest_blogpost,在web/models.py的Tag类中添加:
def get_latest_blogpost(self, count=5):
return self.blogpost_set.order_by('id').reverse()[0:count]
使用方法同上面文章标题用法
本节简答介绍了自定义属性的使用场景和方法,这是在模板中遇到困难时第一个想到的方法,简便易行,下一节我们来介绍丰富的编辑器ckeditor的集成
Recommend
-
101
欢迎大家前往我的个人博客,获取更好的阅读体验和更多分享文章~ 上一章,我们实现了用户的注册和登录,登录之后展示的是我们的主页,页面的左侧是多级的导航菜单,定位并展示用户需要访问的不同...
-
79
ASP.NET Core 一步步搭建个人网站(5)_Api模拟和网站分析 欢迎大家前往
-
49
Github + Hexo + Travis Github 源文件和网站资源的管理 Hexo 网站内容的生成...
-
38
[个人网站搭建]·极简方式实现打赏功能 可以查看我的个人主页,参看效果--> https://xiaosongshine.github.io/ 个人网站搭建github地址:
-
18
...
-
8
从0到1搭建个人网站 八-django中集成ckeditor 全栈技术...
-
5
从0到1搭建个人网站 六-路由的使用 全栈技术...
-
5
使用 Hexo 在 Github 搭建个人网站 下文中的 hexo-template、ar...
-
15
使用 GitBook 在 Github 搭建个人网站 传统的个人网站在某个知名门户下面注册一个子域名,定制个性化内容。 例如 QQ空间、 博客园、 CSDN 等等。 优点: ...
-
7
使用腾讯云DNS解析 + Github Pages,白嫖搭建个人网站 (给小白的保姆级教程) 原创 程序员晚...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK