1. 程式人生 > >Django自定義標籤實現多級評論

Django自定義標籤實現多級評論

  1. 首先在App的目錄下,建一個名為templatetags的Python package(含有init.py)
  2. 在templatetags下新建一個名為custom.py的檔案。

這裡用到了遞迴,去尋找子評論。
在custom.py裡,加入以下程式碼。
這裡寫圖片描述

在models.py裡,對Comment類加上父評論,指向他自己。

parent_comment = models.ForeignKey('self', related_name='p_comment',null=True, blank=True)

在templates裡需要用的html中,加上我們自定義的標籤。

# 在HTML最上面加上這句話
{% load custom %} # 在需要用到多級評論的地方加上這句話,其中comments是view傳過來的,比如comments = article.comment_set.all() {% build_comment_tree comments %}