[個人網站搭建]·Django增加評論功能
個人主頁--> https://xiaosongshine.github.io/
個人網站搭建github地址:https://github.com/xiaosongshine/djangoWebs
安裝django插件
配置settings.py
在INSTALLED_APP添加django_comments和django.contrib.sites兩個應用。
在外部添加 SITE_ID=1。
django的評論庫是一個站點,所以需要添加sites的應用並設置當前django工程的站點id=1
更新數據庫
配置urls.py
在 urlpatterns 中添加
修改前端頁面顯示評論列表和評論提交表單
接着,修改前端頁面顯示評論列表和評論提交表單。這些需要使用django_comments的模版標簽,在使用標簽之前導入加載:
評論列表可以通過django_comments的get_comment_list模版標簽獲取,如下代碼:
get_comment_list模版標簽的用法是for一個模版對象,as是重命名。變量得到的評論加載即可。
而評論提交表單,最主要的是提交的url和表單字段。同樣也可以通過django_comments的模版標簽處理,如下代碼:
這一步需要注意的有兩點
1.{% get_comment_form for blog as blog_form %} {% get_comment_list for blog as comments %}中blog就是你的文章內容,我的主頁用的是show我就改為了:
{% get_comment_form for show as blog_form %} {% get_comment_list for show as comments %}
2.<input type="hidden" name="next" value="{%url 'detailblog' blog.id%}"/>其中的value="{%url 'detailblog' blog.id%}就是你要刷新的網頁url,我的修改為了:
<input type="hidden" name="next" value="/details-{{show.id}}.html"/>
還有一個小技巧:可以通過{{ comments|length}}獲取評論總數目,便於統計顯示,我的實現:
<li><a href="#" class="icon fa-comment">{{ comments|length}}</a></li>
重啟Uwsgi和Nginx
修改Django文件和其它配置文件之后,一定要重啟Uwsgi和Nginx,不然不生效。
Uwsgi和Nginx重啟方法:
效果展示
Please Enjoy Yourself
歡迎大家訪問我的主頁嘗試一下,覺得有用的話,麻煩小小鼓勵一下 ><
個人網站搭建github地址:https://github.com/xiaosongshine/djangoWebs 歡迎訪問