Django - 評論



在開始之前,請注意 Django 評論框架已在 1.5 版本中棄用。現在您可以使用外部功能來實現此目的,但如果您仍然想使用它,它仍然包含在 1.6 和 1.7 版本中。從 1.8 版本開始,它不存在,但您仍然可以在不同的 GitHub 帳戶上獲取程式碼。

評論框架使您可以輕鬆地將評論附加到應用程式中的任何模型。

要開始使用 Django 評論框架 -

編輯專案 settings.py 檔案,並將 'django.contrib.sites''django.contrib.comments' 新增到 INSTALLED_APPS 選項中 -

INSTALLED_APPS += ('django.contrib.sites', 'django.contrib.comments',)

獲取站點 ID -

>>> from django.contrib.sites.models import Site
>>> Site().save()
>>> Site.objects.all()[0].id
u'56194498e13823167dd43c64'

在 settings.py 檔案中設定您獲得的 ID -

SITE_ID = u'56194498e13823167dd43c64'

同步資料庫,以建立所有評論表或集合 -

python manage.py syncdb

將評論應用程式的 URL 新增到專案的 urls.py 中 -

from django.conf.urls import include
url(r'^comments/', include('django.contrib.comments.urls')),

現在我們已經安裝了框架,讓我們更改我們的 hello 模板以跟蹤我們 Dreamreal 模型上的評論。我們將列出、儲存特定 Dreamreal 條目的評論,其名稱將作為引數傳遞給 /myapp/hello URL。

Dreamreal 模型

class Dreamreal(models.Model):

   website = models.CharField(max_length = 50)
   mail = models.CharField(max_length = 50)
   name = models.CharField(max_length = 50)
   phonenumber = models.IntegerField()

   class Meta:
      db_table = "dreamreal"

hello 檢視

def hello(request, Name):
   today = datetime.datetime.now().date()
   daysOfWeek = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
   dreamreal = Dreamreal.objects.get(name = Name)
   return render(request, 'hello.html', locals())

hello.html 模板

{% extends "main_template.html" %}
{% load comments %}
{% block title %}My Hello Page{% endblock %}
{% block content %}

<p>
   Our Dreamreal Entry:
   <p><strong>Name :</strong> {{dreamreal.name}}</p>
   <p><strong>Website :</strong> {{dreamreal.website}}</p>
   <p><strong>Phone :</strong> {{dreamreal.phonenumber}}</p>
   <p><strong>Number of comments :<strong> 
   {% get_comment_count for dreamreal as comment_count %} {{ comment_count }}</p>
   <p>List of comments :</p>
   {% render_comment_list for dreamreal %}
</p>

{% render_comment_form for dreamreal %}
{% endblock %}

最後將 URL 對映到我們的 hello 檢視 -

url(r'^hello/(?P<Name>\w+)/', 'hello', name = 'hello'),

現在,

  • 在我們的模板 (hello.html) 中,使用 - {% load comments %} 載入評論框架

  • 我們獲取檢視傳遞的 Dreamreal 物件的評論數量 - {% get_comment_count for dreamreal as comment_count %}

  • 我們獲取物件的評論列表 - {% render_comment_list for dreamreal %}

  • 我們顯示預設的評論表單 - {% render_comment_form for dreamreal %}

訪問 /myapp/hello/steve 時,您將獲得名稱為 Steve 的 Dreamreal 條目的評論資訊。訪問該 URL 將為您提供 -

Django Comments Example

釋出評論後,您將重定向到以下頁面 -

Comments Redirected Page

如果您再次訪問 /myapp/hello/steve,您將看到以下頁面 -

Number of Comments

如您所見,評論數量現在為 1,並且您在評論列表行下有評論。

廣告