博客-4-点赞、评论

博客主要介绍了路由、视图、HTML文件以及操作点赞的article.js等信息技术相关内容,涵盖前端开发中页面展示、交互操作等方面的关键元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

路由

#一级视图
url(r'(\w+)/article/(\d+)/$', views.article_detail),

#二级视图
url(r"up_down/",views.up_down),
url(r"comment/",views.comment),
url(r"comment_tree/(\d+)/",views.comment_tree),

视图

# 详情页视图
def article_detail(request, username, pk):
	"""
	:param username: 被访问的blog的用户名
	:param pk: 访问的文章的主键id值
	:return: 返回字符串替换HTML文件
	"""
	user = models.UserInfo.objects.filter(username=username).first()
	if not user:
		return HttpResponse("404")
	blog = user.blog
	# 找到当前的文章
	article_obj = models.Article.objects.filter(pk=pk).first()
	# 所有评论列表
	comment_list=models.Comment.objects.filter(article_id=pk)

	return render(
		request,
		"article_detail.html",
		{
			"username": username,
			"article": article_obj,
			"blog": blog,
			"comment_list":comment_list
		 })


# 点赞视图
import json
from django.db.models import F

def up_down(request):
	user = request.user
	article_id=request.POST.get('article_id')
	is_up=json.loads(request.POST.get('is_up'))   
	response={"state":True}
	try:
		# 是否能新建成功
		models.ArticleUpDown.objects.create(user=user,article_id=article_id,is_up=is_up)
		models.Article.objects.filter(pk=article_id).update(up_count=F("up_count")+1)
	# 失败代表已经点赞了
	except Exception as e:
		response["state"]=False
		response["fisrt_action"]=models.ArticleUpDown.objects.filter(user=user,article_id=article_id).first().is_up
	return JsonResponse(response)

#评论视图
def comment(request):

	pid=request.POST.get("pid")
	article_id=request.POST.get("article_id")
	content=request.POST.get("content")
	user_pk=request.user.pk
	response={}
	if not pid:  #根评论
		comment_obj=models.Comment.objects.create(article_id=article_id,user_id=user_pk,content=content)
	else:
		comment_obj=models.Comment.objects.create(article_id=article_id,user_id=user_pk,content=content,parent_comment_id=pid)

	response["create_time"]=comment_obj.create_time.strftime("%Y-%m-%d")
	response["content"]=comment_obj.content
	response["username"]=comment_obj.user.username
	return JsonResponse(response)


# 评论树视图
def comment_tree(request,article_id):
	ret=list(models.Comment.objects.filter(article_id=article_id).values("pk","content","parent_comment_id"))
	
	return JsonResponse(ret,safe=False)

HTML文件

{% extends 'base.html' %}

{% block page-main %}

<div class="article-detail">
    <h1>{{ article.title }}</h1>
    <p>{{ article.articledetail.content|safe }}</p>
</div>

<div class="poll clearfix">
    <div id="div_digg">
        <div class="diggit action">
            <span class="diggnum" id="digg_count">{{ article.up_count }}</span>
        </div>
        <div class="buryit action">
            <span class="burynum" id="bury_count">{{ article.down_count }}</span>
        </div>
        <div class="clear"></div>
        <div class="diggword" id="digg_tips" style="color: red;"></div>
    </div>

</div>
<p>评论树</p>

<div class="comment_tree">

</div>
<hr>
<p>评论列表</p>
<ul class="comment_list">
    {% for comment in comment_list %}
        <li class="list-group-item">
            <div>
                <a href="">#{{ forloop.counter }}楼</a> &nbsp;&nbsp;
                <span style="color: gray">{{ comment.create_time|date:"Y-m-d H:i" }}</span> &nbsp;&nbsp;
                <a href=""><span>{{ comment.user.username }}</span></a>
                <a class="pull-right reply_btn" username="{{ comment.user.username }}"
                   comment_pk="{{ comment.pk }}"><span>回复</span></a>
            </div>
            {% if comment.parent_comment_id %}
                <div class="pid_info well">
                    <p> {{ comment.parent_comment.user.username }}:
                        &nbsp;&nbsp;&nbsp;{{ comment.parent_comment.content }} </p>
                </div>
            {% endif %}

            <div class="con">
                <p>
                    {{ comment.content }}
                </p>
            </div>
        </li>
    {% endfor %}
</ul>

{% if request.user.username %}
    <div class="div_comment">
        <p>昵称:<input type="text" id="tbCommentAuthor" class="author" disabled="disabled" size="50"
                     value="{{ request.user.username }}"></p>
        <p>评论内容</p>
        <textarea name="" id="comment_content" cols="60" rows="10"></textarea>
        <p>
            <button id="comment_btn">提交评论</button>
        </p>

    </div>
{% else %}
    <a href="/login/">登录</a>
{% endif %}



<script>
    // 获取评论数据,展示评论树结构
    $.ajax({
        url: "/blog/comment_tree/" + '{{ article.pk }}/',
        success: function (data) {
            console.log(data);

            $.each(data, function (index, comment_dict) {
                var s = '<div class="comment_item" comment_id=' + comment_dict.pk + '> <span class="content">' + comment_dict.content + '</span> </div>'
                if (comment_dict.parent_comment_id) {
                    // 子评论
                    pid=comment_dict.parent_comment_id;
                    $("[comment_id="+pid+"]").append(s);
                }
                else {   //  根评论
                    $(".comment_tree").append(s);
                }
            })
        }
    });


    // 提交评论
    var pid = "";
    $("#comment_btn").click(function () {

        var article_id = $(".info").attr("article_id");
        var content = $("#comment_content").val();
        if (pid) {
            var index = content.indexOf("\n");
            content = content.slice(index + 1)
        }

        $.ajax({
            url: "/blog/comment/",
            type: "post",
            data: {
                article_id: article_id,
                content: content,
                pid: pid,
                csrfmiddlewaretoken: $("[name='csrfmiddlewaretoken']").val(),
            },
            success: function (data) {
                console.log(data);
                var create_time = data.create_time;
                var content = data.content;
                var username = data.username;


                var comment_li = '<li class="list-group-item"><div><span style="color: gray">' + create_time + '</span> &nbsp;&nbsp; <a href=""><span>' + username + '</span></a></div> <div class="con"> <p> ' + content + ' </p> </div> </li>';

                $(".comment_list").append(comment_li);

                // 清空文本框
                $("#comment_content").val('');
                // 清空pid
                pid = ""
            }
        })
    });


    // 回复按钮事件

    $(".list-group-item .reply_btn").click(function () {

        $("#comment_content").focus();
		
        var v = "@" + $(this).attr("username") + "\n";
        $("#comment_content").val(v);

        //pid赋值
        pid = $(this).attr("comment_pk")
    })

</script>


<div class="info" article_id="{{ article.pk }}" username="{{ request.user.username }}"></div>

{% csrf_token %}

<script src="/static/js/article_detail.js"></script>

{% endblock %}

操作点赞的article.js

$("#div_digg .action").click(function () {

    if ($(".info").attr("username")) {

        // 点赞或踩灭
        var is_up = $(this).hasClass("diggit");
        var article_id = $(".info").attr("article_id");

        $.ajax({
            url: "/blog/up_down/",
            type: "post",
            data: {
                is_up: is_up,
                article_id: article_id,
                csrfmiddlewaretoken: $("[name='csrfmiddlewaretoken']").val(),
            },
            success: function (data) {
                console.log(data);


                if (data.state) {// 赞或者灭成功

                    if (is_up) {
                        var val = $("#digg_count").text();
                        val = parseInt(val) + 1;
                        $("#digg_count").text(val);
                    } else {
                        var val = $("#bury_count").text();
                        val = parseInt(val) + 1;
                        $("#bury_count").text(val);
                    }
                }
                else {    // 重复提交

                    if (data.fisrt_action) {
                        $("#digg_tips").html("您已经推荐过");
                    } else {
                        $("#digg_tips").html("您已经反对过");
                    }

                    setTimeout(function () {
                        $("#digg_tips").html("")
                    }, 1000)
                }
            }
        })

    }
    else {
        location.href = "/login/"
    }

});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值