今天尝试为自己开发的博客加上评论功能,查看Django的文档,发现1.6之后Django不再自带comments这个app了,下面是官方文档上的说明:
Django’s comment framework has been deprecated and is no longer supported. Most users will be better served with a custom solution, or a hosted product like Disqus.
The code formerly known as django.contrib.comments is still available in an external repository.
虽然不再自带,但是仍然可以自己安装实现。根据文档的指引打开下面这个网址
http://django-contrib-comments.readthedocs.org/en/latest/index.html 根据网站中所示的步骤一步一步进行操作:
1. Install the comments app by running pip install django-contrib-comments.
2. Install the comments framework by adding 'django_comments' to INSTALLED_APPS.
3. Run manage.py syncdb so that Django will create the comment tables.
4. Add the comment app’s URLs to your project’s urls.py:
urlpatterns = patterns('', ... (r'^comments/', include('django_comments.urls')), ... )
5. Use the comment template tags below to embed comments in your templates.
这里需要注意在settings.py的INSTALLED_APPS中,除了增加django_comments外,还需要增加django.contrib.sites,就像这样:
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
'text_markup',
'django.contrib.sites',
'django_comments',
)
然后我试着在模板中调用comments:
{% load comments %}
{% get_comment_count for post as comment_count %}
保存后打开网页,会抛出错误提示:AttributeError: 'Settings' object has no attribute 'SITE_ID'
上网搜索了一下,查得这是因为在settings.py中没有指定SITE_ID导致,我猜测是因为刚刚添加的django.contrib.sites需要指定SITE_ID。在settings.py中任意地方添加SITE_ID=1,问题解决。