Django添加Tag功能
2021-01-25 | Tags: 博客搭建
最近记了一些读书笔记,需要一个Tag的功能把同一类的笔记记录一下,因此就做了一个简单的Tag功能。
Models
首先在models.py中添加一个Tag的model
class Tag(models.Model):
tagname = models.CharField(max_length=20)
def __str__(self):
return self.tagname
对于Tag和Article来说,是一个多对多的关系,在model中实现这样的关系可以参见2.2Doc
因此在Article类中添加一个tags字段
tags = models.ManyToManyField(Tag)
这样对于Tag功能的model设计就完成了
Views
然后在views.py中为每个article渲染传tags进去
tags = article.tags.all().order_by('id')
if article is not None:
return render(request, 'main/article.html', {
'article':article,
'date': article.date.strftime("%Y-%m-%d"),
'content': markdown.markdown(article.content),
'tags': tags
})
并且在template中添加对应tags的渲染代码
{% if tags|length > 0 %}
| Tags:
{% for tag in tags %}
<a href="/tag/{{ tag.id }}"> {{ tag.tagname }}</a>
{% endfor %}
{% endif %}
就可以在article页面看到渲染出来的tags列表了
Tag的article列表
另外对于每个Tag,还需要一个包含整个Tag的article列表页面,可以通过/tag/{{ tag.id }}的格式进入。
首先在urls.py中添加对这个url的路由规则
path('tag/<int:tag_id>', main_views.tag_index, name='tag_index'),
在views.py中添加tag_index函数
def tag_index(request, tag_id):
try:
tag = Tag.objects.get(id=tag_id)
articles = tag.article_set.filter(is_show=True).order_by('-date')
context = {
'tag': tag.tagname,
'articles': articles,
}
return render(request, 'main/index.html', context)
except Exception as e:
print(e.with_traceback, e)
这里article列表复用了index的article列表,但是特别显示了一下当前的tag名,在template下的index.html中添加相关判断
{% if tag is not None %}
<p><b>|Tag:
{{ tag }}
</b></p>
{% endif %}
到这里Tag相关功能的简单实现就完成了,tag的article列表效果可以访问博客搭建Tag查看
源码
最后这个tag功能的commit已经更新,可以到github访问