じゅう迁央、構(gòu)建評論系統(tǒng)

操作步驟:

  1. 創(chuàng)建模型保存評論內(nèi)容
  2. 創(chuàng)建表單掷匠,從而可提交評論內(nèi)容并對數(shù)據(jù)進(jìn)行驗(yàn)證。
  3. 添加包含該表單的視圖岖圈,并將最新的評論內(nèi)容添加至數(shù)據(jù)庫中讹语。
  4. 標(biāo)記帖子的詳細(xì)模板,以顯示評論列表和添加新評論的表單蜂科。

1. 創(chuàng)建模型

1.1 編輯blog應(yīng)用程序的models.py文件顽决,添加以下代碼:

class Comment(models.Model):
    post = models.ForeignKey(Post,
                             on_delete=models.CASCADE,
                             related_name='comments')
    name = models.CharField(max_length=80)
    email = models.EmailField()
    body = models.TextField()
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    active = models.BooleanField(default=True)

    class Meta:
        ordering = ('-created',)

    def __str__(self):
        return "Comment by {} on {}.".format(self.name,self.post)

1.2. 同步到數(shù)據(jù)庫

(my_env) zzx@zzx:~/mysite$ python manage.py makemigrations blog
輸出如下:

Migrations for 'blog':
  blog/migrations/0002_comment.py
    - Create model Comment

(my_env) zzx@zzx:~/mysite$ python manage.py migrate
輸出如下:

Operations to perform:
  Apply all migrations: admin, auth, blog, contenttypes, sessions
Running migrations:

1.3. 將新模型添加到管理站點(diǎn)中

from .models import Post,Comment

@admin.register(Comment)
class CommentAdmin(admin.ModelAdmin):
    list_display = ('name','email','post','created','active')
    list_filter = ('active','created','updated')

2. 創(chuàng)建模型中的表單

編輯blog應(yīng)用程序的forms.py文件,并添加下列代碼:

from .models import Comment

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment

針對CommentForm表單导匣,僅需使用name才菠、email和body字段——這些字段僅是用戶可填寫的字段。

3. 添加視圖

編輯views.py文件贡定,修改post_detail視圖赋访,如下所示:

from .models import Post,Comment
from .forms import EmailPostForm,CommentForm

def post_detail(request,year,month,day,post):
    post = get_object_or_404(Post,slug=post,
                                  status='published',
                                  publish__year=year,
                                  publish__month=month,
                                  publish__day=day)
    # List of active comments for this post
    comments = post.comments.filter(active=True)

    new_comment = None

    if request.method == 'POST':
        # A comment was posted
        comment_form = CommentForm(data=request.POST)
        if comment_form.is_valid():
            # Create Comment object but don't save to database yet
            new_comment = comment_form.save(commit=False)
            # Assign the current post to the comment
            new_comment.post = post
            # Save the comment to the database
            new_comment.save()
    else:
        comment_form = CommentForm()
    return render(request,
                  'blog/post/detail.html',
                  {'post':post,
                   'comments':comments,
                   'new_comment':new_comment,
                   'comment_form':comment_form})

4. 模板

使用post/detail.html模板執(zhí)行下列操作:

  • 顯示帖子的全部評論數(shù)量
  • 顯示評論列表
  • 向用戶展示一個表單,并可添加新的評論內(nèi)容

4.1 顯示帖子的全部評論數(shù)量

    {% with comments.count as total_comments %}
    <h2>{{ total_comments }} comment{{ total_comments|pluralize }}</h2>
    {% endwith %}

4.2 顯示評論列表

    {% for comment in comments %}
    <div class="comment">
      <p class="info">
        Comment {{ forloop.counter }} by {{ comment.name }} on
        {{ comment.created }}
      </p>
      {{ comment.body|linebreaks }}
    </div>
    {% empty %}
    <p>There are no comments yet.</p>
    {% endfor %}

4.3 向用戶展示一個表單缓待,并可添加新的評論內(nèi)容

    {% if new_comment %}
      <h2>Your comment has been added.</h2>
    {% else %}
      <h2>Add a new comment</h2>
      <form action="." method="post">
        {{ comment_form.as_p }}
        {% csrf_token %}
        <p><input type="submit" value="Add comment"></p>
      </form>
    {% endif %}

最終效果如下:


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末蚓耽,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子命斧,更是在濱河造成了極大的恐慌,老刑警劉巖嘱兼,帶你破解...
    沈念sama閱讀 216,591評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件国葬,死亡現(xiàn)場離奇詭異,居然都是意外死亡芹壕,警方通過查閱死者的電腦和手機(jī)汇四,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,448評論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來踢涌,“玉大人通孽,你說我怎么就攤上這事≌霰冢” “怎么了背苦?”我有些...
    開封第一講書人閱讀 162,823評論 0 353
  • 文/不壞的土叔 我叫張陵互捌,是天一觀的道長。 經(jīng)常有香客問我行剂,道長秕噪,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,204評論 1 292
  • 正文 為了忘掉前任厚宰,我火速辦了婚禮腌巾,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘铲觉。我一直安慰自己澈蝙,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,228評論 6 388
  • 文/花漫 我一把揭開白布撵幽。 她就那樣靜靜地躺著灯荧,像睡著了一般。 火紅的嫁衣襯著肌膚如雪并齐。 梳的紋絲不亂的頭發(fā)上漏麦,一...
    開封第一講書人閱讀 51,190評論 1 299
  • 那天,我揣著相機(jī)與錄音况褪,去河邊找鬼撕贞。 笑死,一個胖子當(dāng)著我的面吹牛测垛,可吹牛的內(nèi)容都是我干的捏膨。 我是一名探鬼主播,決...
    沈念sama閱讀 40,078評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼食侮,長吁一口氣:“原來是場噩夢啊……” “哼号涯!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起锯七,我...
    開封第一講書人閱讀 38,923評論 0 274
  • 序言:老撾萬榮一對情侶失蹤链快,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后眉尸,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體域蜗,經(jīng)...
    沈念sama閱讀 45,334評論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,550評論 2 333
  • 正文 我和宋清朗相戀三年噪猾,在試婚紗的時候發(fā)現(xiàn)自己被綠了霉祸。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,727評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡袱蜡,死狀恐怖丝蹭,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情坪蚁,我是刑警寧澤奔穿,帶...
    沈念sama閱讀 35,428評論 5 343
  • 正文 年R本政府宣布镜沽,位于F島的核電站,受9級特大地震影響巫橄,放射性物質(zhì)發(fā)生泄漏淘邻。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,022評論 3 326
  • 文/蒙蒙 一湘换、第九天 我趴在偏房一處隱蔽的房頂上張望宾舅。 院中可真熱鬧,春花似錦彩倚、人聲如沸筹我。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,672評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽蔬蕊。三九已至,卻和暖如春哥谷,著一層夾襖步出監(jiān)牢的瞬間岸夯,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,826評論 1 269
  • 我被黑心中介騙來泰國打工们妥, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留猜扮,地道東北人。 一個月前我還...
    沈念sama閱讀 47,734評論 2 368
  • 正文 我出身青樓监婶,卻偏偏與公主長得像旅赢,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子惑惶,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,619評論 2 354