Django有自带的评论库组建,1.6之后的版本需要自行安装
1. 安装
pip install django-contrib-comments
2. 设置
django的评论库是一个站点,所以需要添加sites的应用并设置当前django工程的站点id=1
- 在INSTALLED_APP添加django_comments和django.contrib.sites两个应用。
- 在外部添加 SITE_ID=1。
setting.py
INSTALLED_APP=(
#...,
'django_comments',
'django.contrib.sites',
)
SITE_ID = 1
3. 路由配置以及数据同步
在urls.py添加django_comments的路由设置
url(r'^comments/', include('django_comments.urls')),
- 之后执行 python ./manage.py syncdb 同步一下数据库即可。
- 之后在使用评论库模板标签时需要使用
{% load comments %}
导入加载
4. 使用
i. 获取评论列表—— get_comment_list
模版标签
get_comment_list模版标签的用法是for一个模版对象,as是重命名。变量得到的评论加载即可。
<div class="panel panel-default">
<div class="panel-heading">
<h4>评论列表</h4>
</div>
<div class="panel-body">
{% get_comment_list for blog as comments %}
{% for comment in comments %}
<div class="blog_comment" name="F{{comment.id}}">
<p class="comment_title">
#{{ comment.submit_date|date:"Y-m-d H:i"}} @ {{ comment.user_name }}:
</p>
<p class="comment_content">{{ comment.comment }}</p>
</div>
{% empty %}
<span>暂无评论</span>
{% endfor %}
</div>
</div>
ii. 评论提交
评论提交表单,最主要的是提交的url和表单字段。同样也可以通过django_comments的模版标签处理
<h4>新的评论</h4>
{% get_comment_form for blog as blog_form %}
<form id="comment_form"
class="form-horizontal"
action="{% comment_form_target %}"
method="post"
>
{% csrf_token %}
{# 必须的字段 #}
{{ blog_form.object_pk }}
{{ blog_form.content_type }}
{{ blog_form.timestamp }}
{{ blog_form.site }}
{{ blog_form.submit_date }}
{{ blog_form.security_hash }}
{# 用户名字段,这个后面会修改为登录用户评论,无需填这个 #}
<div class="control-group">
<label class="control-label" for="id_name">名称: </label>
<div class="controls">
<input type="text"
id="id_name" class="input-xlarge" name="name"
placeholder="请输入您的用户名"
value="{{ user.username }}" />
</div>
</div>
{# 邮箱地址字段 #}
<div class="control-group">
<label class="control-label" for="id_email">邮箱: </label>
<div class="controls">
<input type="email"
id="id_email" class="input-xlarge" name="email"
placeholder="请输入您的邮箱地址"
value="{{ user.email }}" />
</div>
</div>
{# 评论内容 #}
<a name="newcomment" id="newcomment"></a>
<div class="control-group">
<label class="control-label" for="id_comment">评论: </label>
<div class="controls">
<textarea rows="6"
id="id_comment" class="input-xlarge comment" name="comment"
placeholder="请输入评论内容">
</textarea>
</div>
</div>
{# 防垃圾评论 #}
<p style="display:none;">
<label for="id_honeypot">如果你在该字段中输入任何内容,你的评论就会被视为垃圾评论。</label>
<input type="text" name="honeypot" id="id_honeypot">
</p>
{# 表单按钮 #}
<div class="controls">
<div class="form-actions">
<input class="btn btn-info" id="submit_btn" type="submit" name="submit" value="提交"/>
<input type="hidden" name="next" value="{%url 'detailblog' blog.id%}"/>
</div>
</div>
</form>
网友评论