天天看點

BBS(仿部落格園系統)項目04(文章詳情頁根評論、子評論的功能實作)

摘要:

  • 根評論(文章的普通評論)
  • 子評論(一篇文章中評論的評論)

一、根評論(普通的評論)

①文章詳情下方點贊的下方評論區頁面的搭建(渲染):

article_detail.html頁面:

{#    評論開始#}
{#    使用者如果登入,才具有評論的權力,否則評論頁面不予顯示#}
    {% if request.user.is_authenticated %}
        <div>
            <div>
                <p><span class="glyphicon glyphicon-comment">發表評論</span></p>
                <p>昵稱:<input type="text" class="from-control" disabled value="{{ request.user.username }}"></p>
                <p>評論内容:</p>
                <p><textarea name="content" id="content" cols="60" rows="10"></textarea></p>
                <p>
                    <button class="btn btn-default" id="comment_submit">送出評論</button>
                    <span style="color: red;" id="submit_info"></span>
                </p>
            </div>
        </div>
    {% endif %}
{#    評論結束#}      

這裡送出評論的資料請求到後端,需要建立一個路由專門處理評論資料

urls.py路由檔案

url(r'^comment/', views.comment),

一定要放在它上面,不然會被它攔截比對
    url(r'^(?P<username>\w+)/$', views.blog),      

先看看效果

BBS(仿部落格園系統)項目04(文章詳情頁根評論、子評論的功能實作)

點選送出評論,使用ajax向後端發送請求,後端進行相關判斷,響應評論送出請求

article_detail.html頁面script内

// 送出評論開始
    $('#comment_submit').on('click',function () {
        $.ajax({
            url:'/comment/',
            type: 'post',
            data: {
                'csrfmiddlewaretoken': '{{ csrf_token }}',
                'article_id': '{{ article_obj.pk }}',
                'content': $('#content').val(),
            },
            success:function (data) {
                if (data.code==100){
                    $('#submit_info').html(data.msg);
                    $('#temp_comment').removeClass('hide').children('.bq_post_comment').html($('#content').val())
                }
                else {$('#submit_info').html(data.msg);}
                $('#content').val('')
            }
        })
    });
// 送出評論結束      

views.py中comment視圖函數:

def comment(request):
    if request.is_ajax():
        back_dic = {'code': 100, 'msg': ''}
        article_id = request.POST.get('article_id')
        content = request.POST.get('content')
        # 後端再校驗使用者是否登入
        if request.user.is_authenticated():
            # 開啟事務:同步更新2張表
            # from django.db import transaction
            with transaction.atomic():
                # 更新2張表:一張Article,一張Comment表
                models.Article.objects.filter(pk=article_id).update(comment_num=F('comment_num')+1)
                models.Comment.objects.create(user=request.user, article_id=article_id, content=content)
                back_dic['msg'] = '評論成功'
        else:
            back_dic['code'] = 200
            back_dic['msg'] = '請先登入'
        return JsonResponse(back_dic)      
BBS(仿部落格園系統)項目04(文章詳情頁根評論、子評論的功能實作)

這裡補充一點:點贊點踩部分會出現浮動塌陷現象,需要在點贊點踩整個标簽外套一個div标簽,然後在改标簽的class類中添加clearfix,即可解決塌陷問題

BBS(仿部落格園系統)項目04(文章詳情頁根評論、子評論的功能實作)

接下來渲染文章下面的所有評論展示區域

{#評論展示開始#}
{% if comment_list %}  # 判斷有無評論,如果有評論踩渲染評論區域
    <div>
        <h4 class="comment_top"><b>評論清單</b></h4>
        {% for comment in comment_list %}
            <p>
                <span>#{{ forloop.counter }}樓</span>
                <span>{{ comment.create_time|date:'Y-m-d' }}</span>
                <span><a href="/{{ comment.user.username }}/">{{ comment.user.username }}</a></span>
                <span class="pull-right"><a href="">回複</a></span>
            </p>
            <p><span>{{ comment.content }}</span></p>
            <hr>
        {% endfor %}
        <div class="hide" id="temp_comment">
            <span class="glyphicon glyphicon-comment"></span>
            <a href="/{{ comment.user.username }}/"><b>{{ request.user.username }}:</b></a>
            <blockquote class="bq_post_comment"></blockquote>
        </div>
    </div>
{% endif %}
{#評論展示結束#}      

先看效果圖再分析

BBS(仿部落格園系統)項目04(文章詳情頁根評論、子評論的功能實作)
BBS(仿部落格園系統)項目04(文章詳情頁根評論、子評論的功能實作)

評論後動态臨時展示的使用者評論資訊的方法二:

BBS(仿部落格園系統)項目04(文章詳情頁根評論、子評論的功能實作)
BBS(仿部落格園系統)項目04(文章詳情頁根評論、子評論的功能實作)

評論清單需要設定樣式,以達到展示效果

.comment_top {
        font-weight: bold;
        border-bottom: 1px solid #333;
        font-size: 1.2em;
        padding: 0 0 8px 1px;
    }
      

 至此文章詳情的普通評論功能實作完成,最後看看效果:

BBS(仿部落格園系統)項目04(文章詳情頁根評論、子評論的功能實作)

二、子評論(一篇文章中評論的評論)

 第一步:點選回複标簽完成如下三件事:

  • 1.把你想評論的那條評論的人名自動添加到textarea中(@+使用者名)
  • 2.自動換行
  • 3.textarea自動聚焦

實作:

首先:在回複标簽中添加2個屬性:username和comment_id

BBS(仿部落格園系統)項目04(文章詳情頁根評論、子評論的功能實作)

然後:捕獲點選事件,進行操作

$('.reply').on('click',function () {
    // 回複時自動将回複的目标使用者名添加到area框中:
    let rUsername=$(this).attr('username');
    let rCommentid=$(this).attr('comment_id');
    // @+使用者名+自動換行
    $('#content').val('@'+rUsername+'\n');
    // textarea自動聚焦
    $('#content').focus()
});      
BBS(仿部落格園系統)項目04(文章詳情頁根評論、子評論的功能實作)

 第二步:判斷根評論和子評論,進行後端資料操作

分析:

①一開始我們進行普通評論(也就是根評論)的時候,并沒有在後端更新評論記錄時加上parent_id值,因為該值我們在定義表的時候預設設定可以為空,它正好也符合根評論的需要,隻有子評論時候parent_id才會有值。

②那麼我們在進行子評論的時候,也就是點選回複,編寫評論,然後也是點選同一個送出按鈕時候,應該如何判斷我送出的是根評論還是子評論呢?

③後端處理根評論還是子評論其實流程都是一樣的,不一樣的地方隻在create評論表記錄時候,parent_id有值,是以可以在前端将parent_id傳過去,如果是根評論則傳空,如果是子評論正常傳對應評論的評論id就行,create裡面加入parent_id=傳入的值。

通過上面分析開始實作:

BBS(仿部落格園系統)項目04(文章詳情頁根評論、子評論的功能實作)
BBS(仿部落格園系統)項目04(文章詳情頁根評論、子評論的功能實作)
BBS(仿部落格園系統)項目04(文章詳情頁根評論、子評論的功能實作)
BBS(仿部落格園系統)項目04(文章詳情頁根評論、子評論的功能實作)

 接下來測試:

BBS(仿部落格園系統)項目04(文章詳情頁根評論、子評論的功能實作)
BBS(仿部落格園系統)項目04(文章詳情頁根評論、子評論的功能實作)

可以看出,區分子評論和根評論已經沒問題

但是仔細看評論顯示樓的子評論發現評論内容前面加了個@使用者名

正常顯示應該是這樣的:

BBS(仿部落格園系統)項目04(文章詳情頁根評論、子評論的功能實作)

 繼續修改評論樓區html代碼:

BBS(仿部落格園系統)項目04(文章詳情頁根評論、子評論的功能實作)

接下來我們看上面的評論表資料,發現評論内容前面都有@使用者名的字元串,這顯然不是評論的内容,需要清除:

BBS(仿部落格園系統)項目04(文章詳情頁根評論、子評論的功能實作)

此時子評論内容正常顯示,查詢資料表記錄評論内容也正常。

到這裡根評論子評論基本上功能全部實作,但是這裡還有一個問題需要稍微解決一下:

分析:前面我們定義了一個全局變量parentId,用于區分根評論和子評論,但是這裡有個問題:

當我們送出了子評論後,如果不點重新整理,繼續送出根評論,此時的全局parentId還是有值的,這時候送出根評論就會出現問題----送出的是根評論,結果是子評論

解決辦法:

在送出過後将parentId置空

BBS(仿部落格園系統)項目04(文章詳情頁根評論、子評論的功能實作)

最後附上根評論子評論代碼:

 article_detail.html

BBS(仿部落格園系統)項目04(文章詳情頁根評論、子評論的功能實作)
BBS(仿部落格園系統)項目04(文章詳情頁根評論、子評論的功能實作)
{% extends 'base.html' %}
{% block css %}
    <style>
    #temp_info {
    margin: 0 0 5px 0;
    font-style: normal;
    font-size: 13px;
    line-height: 180%;
    border: 1px solid #ddd;
    padding: 10px;
}
    #div_digg {
    float: right;
    margin-bottom: 10px;
    margin-right: 30px;
    font-size: 12px;
    width: 125px;
    text-align: center;
    margin-top: 10px;
}
    .diggit {
    float: left;
    width: 46px;
    height: 52px;
    background: url(/static/upup.gif) no-repeat;
    text-align: center;
    cursor: pointer;
    margin-top: 2px;
    padding-top: 5px;
}
    .buryit {
    float: right;
    margin-left: 20px;
    width: 46px;
    height: 52px;
    background: url(/static/downdown.gif) no-repeat;
    text-align: center;
    cursor: pointer;
    margin-top: 2px;
    padding-top: 5px;
}
    .clear {
    clear: both;
}
    .diggword {
    margin-top: 5px;
    margin-left: 0;
    font-size: 12px;
    color: gray;
}
    div input {
    background-color: white;
    background-image: url(/static/icon_form.gif);
    background-repeat: no-repeat;
    border: 1px solid #ccc;
    padding: 6px 4px 4px 30px;
    width: 300px;
    font-size: 13px;}
    .comment_top {
        font-weight: bold;
        border-bottom: 1px solid #333;
        font-size: 1.2em;
        padding: 0 0 8px 1px;
    }
    </style>

{% endblock %}

{% block content %}
    <h2>{{ article_obj.title }}</h2>
    {{ article_obj.content|safe }}
{#    點贊點踩開始#}
    <div class="clearfix">
        <div id="div_digg">
            <div class="diggit action">
                <span class="diggnum" id="digg_count">{{ article_obj.up_num }}</span>
            </div>
            <div class="buryit action">
                <span class="burynum" id="bury_count">{{ article_obj.down_num }}</span>
            </div>
            <div class="clear"></div>
            <div class="diggword" id="digg_tips" style="color: red"></div>
        </div>
    </div>

{#    點贊點踩結束#}
{#評論展示開始#}
{% if comment_list %}
    <div>
        <h4 class="comment_top"><b>評論清單</b></h4>
        {% for comment in comment_list %}
            <p>
                <span>#{{ forloop.counter }}樓</span>
                <span>{{ comment.create_time|date:'Y-m-d' }}</span>
                <span><a href="/{{ comment.user.username }}/">{{ comment.user.username }}</a></span>
                <span class="pull-right reply" username="{{ comment.user.username }}" comment_id="{{ comment.pk }}">
                    <a>回複</a></span>
            </p>
            <div>
            {% if comment.parent %}
                <p>@&nbsp;{{ comment.parent.user.username }}</p>
            {% endif %}
                <span>{{ comment.content }}</span>
            </div>
            <hr>
        {% endfor %}
    </div>
{% endif %}
    <div id="temp_comment"></div>
{#    <div class="hide" id="temp_comment">#}
{#        <span class="glyphicon glyphicon-comment"></span>#}
{#        <a href="/{{ comment.user.username }}/"><b>{{ request.user.username }}:</b></a>#}
{#        <blockquote class="bq_post_comment"></blockquote>#}
{#    </div>#}
{#評論展示結束#}
{#    評論開始#}
{#    使用者如果登入,才具有評論的權力,否則評論頁面不予顯示#}
    {% if request.user.is_authenticated %}
        <div>
            <div>

                <p><span class="glyphicon glyphicon-comment">發表評論</span></p>
                <p>昵稱:<input type="text" class="from-control" disabled value="{{ request.user.username }}"></p>
                <p>評論内容:</p>
                <p><textarea name="content" id="content" cols="60" rows="10"></textarea></p>
                <p>
                    <button class="btn btn-default" id="comment_submit">送出評論</button>
                    <span style="color: red;" id="submit_info"></span>
                </p>

            </div>
        </div>
    {% endif %}
{#    評論結束#}
{% endblock %}

{% block js %}
<script>
// 在script腳本全局定義一個parentId預設為空
let parentId='';

// 回複子評論開始
$('.reply').on('click',function () {
    // 回複時自動将回複的目标使用者名添加到area框中:
    let rUsername=$(this).attr('username');
    let rCommentid=$(this).attr('comment_id');
    // @+使用者名+自動換行
    $('#content').val('@'+rUsername+'\n');
    // textarea自動聚焦
    $('#content').focus();
    // 當進行子評論時候,在回複點選事件中将全局parentId指派
    parentId=rCommentid
});

// 回複子評論結束


// 送出評論開始
    $('#comment_submit').on('click',function () {
        // 得到評論内容
        let finalContent=$('#content').val();
        // 判斷評論是否為子評論,如果是,則攔截它,将它進行切分,再走下面代碼
        if(parentId){
            //這裡分析需要切分的子評論内容格式@使用者名\n評論内容,是以切分可以已經\n來切
            //通過indexOf()方法找到\n在子評論字元串中的位置索引,我們要的是\n後面的字元串,是以索引+1
            let indexVal = finalContent.indexOf('\n')+1;
            // 使用slice方法切分,slice方法如果傳入一個值,則從該值得索引位置切到最後
            finalContent=finalContent.slice(indexVal)
        }

        $.ajax({
            url:'/comment/',
            type: 'post',
            data: {
                'csrfmiddlewaretoken': '{{ csrf_token }}',
                'article_id': '{{ article_obj.pk }}',
                'content': finalContent,
                // 在送出按鈕點選事件内加入parent_id,傳入後端,如果是子評論,肯定會走回複按鈕點選事件
                // 進而将parentId指派,然後在點選送出此時parent_id就有值了,如果不點回複評論,那就是根評論,
                // 那麼parent_id預設為空不變。
                'parent_id': parentId,
            },
            success:function (data) {
                if (data.code==100){
                    $('#submit_info').html(data.msg);
                    {#$('#temp_comment').removeClass('hide').children('.bq_post_comment').html($('#content').val())#}
                    let conTent = finalContent;
                    let userName = '{{ request.user.username }}';
                    let tempStr = `
                        <div>
                        <span class="glyphicon glyphicon-comment"></span>
                        <a href="/${userName}/"><b>${userName}</b></a>
                        <p id="temp_info">${finalContent}</p>
                        </div> `;
                    $('#temp_comment').append(tempStr)

                }
                else {$('#submit_info').html(data.msg);}
                $('#content').val('');
                // 将parentId清空
                parentId=''
            }
        })
    });
// 送出評論結束
//點贊點踩開始
    $('.action').on('click',function () {
        let isUp = $(this).hasClass('diggit');
        let $span = $(this).children();
        let $info = $('#digg_tips');
        $.ajax({
            // 這裡判斷點贊點踩的操作涉及多種情況的判斷,應該單獨建立一個url路由
            url:'/up_down/',
            type: 'post',
            // 這裡我們隻需要傳2個關鍵參數:文章id和點贊還是點踩到後端就可以了,因為在後端可以通過request.user來擷取到使用者對象
            data: {
                'article_id': {{ article_obj.pk }},
                // 需要注意這裡的isUp是字元串類型的true或false,在後端需要轉換一下才行
                'is_up': isUp,
                // 别忘了csrf_token
                'csrfmiddlewaretoken': '{{ csrf_token }}'},
            success:function (data) {
                if(data.code==100){
                   $span.html(Number($span.html())+1)
                }else {
                    $info.html(data.msg)
                }
            }
        })
    })
// 點贊點踩結束
</script>
{% endblock %}      

article_detail.html

 views.py

BBS(仿部落格園系統)項目04(文章詳情頁根評論、子評論的功能實作)
BBS(仿部落格園系統)項目04(文章詳情頁根評論、子評論的功能實作)
def comment(request):
    if request.is_ajax():
        back_dic = {'code': 100, 'msg': ''}
        article_id = request.POST.get('article_id')
        content = request.POST.get('content')
        parent_id = request.POST.get('parent_id')
        # 後端再校驗使用者是否登入
        if request.user.is_authenticated():
            # 開啟事務:同步更新2張表
            # from django.db import transaction
            with transaction.atomic():
                # 更新2張表:一張Article,一張Comment表
                models.Article.objects.filter(pk=article_id).update(comment_num=F('comment_num')+1)
                models.Comment.objects.create(user=request.user, article_id=article_id, content=content, parent_id=parent_id)
                back_dic['msg'] = '評論成功'
        else:
            back_dic['code'] = 200
            back_dic['msg'] = '請先登入'
        return JsonResponse(back_dic)      

comment視圖函數

請相信自己

當我們迷茫,懶惰,退縮的時候

我們會格外的相信命運

相信一切都是命中注定

而當我們努力拼搏,積極向上時

我們會格外的相信自己

是以命運是什麼呢?

它是如果你習慣它

那它就會一直左右你

如果你想掙脫它

那它就成為你的阻礙

可如果你打破了它

那它就是你人生的墊腳石!

如果覺得這篇文章對你有小小的幫助的話,記得在右下角點個“推薦”哦,部落客在此感謝!