其他分享
首页 > 其他分享> > 25Django-实现文章详情页的留言和回复功能

25Django-实现文章详情页的留言和回复功能

作者:互联网

把留言和回复都放到一张表里,然后给回复加一个标记,标记一下它是谁的回复,通过上节的案例可以启发:

我把所有的浏览和回复通过sql语句给它查出来,然后我通过上节的方法,把对应的回复都关联到各自的留言里,形成这么一个结构:

[{'name': 'leader-1', 'team': [{'name': 'lili'}, {'name': 'Tom'}]}, {'name': 'leader-2', 'team': [{'name': 'jack'}]}]

 

一实现发布留言:

1创建应用:

D:\PycharmProjects\linuxTangblog>python manage.py startapp message

2添加应用:

INSTALLED_APPS = [
    'message',
]

3编写模型类:

from user.models import UserProfile
from topic.models import Topic
class Message(models.Model):
    content =models.CharField(max_length=50,verbose_name='留言内容')
    created_time = models.DateTimeField(auto_now_add=True)
    parent_message = models.IntegerField(verbose_name='回复的留言id')
    publisher = models.ForeignKey(UserProfile,on_delete=models.CASCADE)
    topic = models.ForeignKey(Topic,on_delete=models.CASCADE)

4同步数据库:

D:\PycharmProjects\linuxTangblog>python manage.py makemigrations
D:\PycharmProjects\linuxTangblog>python manage.py migrate

5配置主路由:

path('v1/messages/',include('message.urls')),

6配置子路由:

from django.urls import path
from . import views
urlpatterns = [
    path('<int:topic_id>',views.message_view),
]

7编写视图:

先实现发布留言功能

from django.http import JsonResponse
from django.shortcuts import render
from tools.logging_dec import logging_check
import json
from topic.models import Topic
from message.models import Message
# Create your views here.
@logging_check
def message_view(request,topic_id):
    #取出当前登录的用户
    user = request.myuser
    #取出所有数据
    json_str = request.body
    #把获取的json串转换为python对象
    json_obj = json.loads(json_str)
    #取出留言内容
    content = json_obj['content']
    #此值有可能取不到,给个默认值
    parent_id = json_obj.get('parent_id',0)
    #尝试获取一下文章
    try:
        topic = Topic.objects.get(id=topic_id)
    except Exception as e:
        result = {'code':10400,'error':'文章不存在'}
        return JsonResponse(result)
    #创建消息数据
    #文章字段等于当前获取的文章,留言字段等于当前获取的content内容,回复的留言id等于当前获取的parent_id,发布者等于当前用户
    Message.objects.create(topic=topic,content=content,parent_message=parent_id,publisher=user)

    return JsonResponse({'code':200})

二实现查看留言:

因为留言在文章详情页里,所以我们需要把留言内容从数据库里取出来后,然后在文章详情页里组织数据

1打开topic/views.py,找到make_topic_res这个方法,在这个方法里有一个res[ 'data' ] ['messages'],我们之前给的是一个空值[ ]

#查出当前文章的所有留言,相当于拿到了春游的原始数据
        all_messages = Message.objects.filter(topic=author_topic).order_by('-created_time')
        #准备一个数组存留言,准备一个字段存回复
        msg_list = []
        rep_dic = {}
        m_count = 0
        #判断身份
        for msg in all_messages:
            if msg.parent_message:
                #回复
                #初始化留言字典框架
                rep_dic.setdefault(msg.parent_message,[])
                rep_dic[msg.parent_message].append({'msg_id':msg.id,'publisher':msg.publisher.nickname,'publisher_avatr':str(msg.publisher.avatar),'content':msg.content,'created_time':msg.created_time.strftime('%Y-%m-%d %H:%M:%S')})

            else:
                #留言
                #计数
                m_count += 1
                msg_list.append({'id':msg.id,'content':msg.content,'publisher':msg.publisher.nickname,'publisher_avatar':str(msg.publisher.avatar),'created_time':msg.created_time.strftime('%Y-%m-%d %H:%M:%S'),'reply':[]})
        #关联回复和留言
        #判断留言id是否在留言回复里,如果在就证明有留言,就把数据存入到reply里
        for m in msg_list:
            if m['id'] in rep_dic:
                m['reply'] = rep_dic[m['id']]

2把组装数据里设的控制不全:

res['data']['messages'] = msg_list
res['data']['messages_count'] = m_count

最后完整浏览一下代码:

class TopicViews(View):#组装文章详情页数据
    def make_topic_res(self,author,author_topic,is_self):
        #博主访问自己
        if is_self:
            #下一篇
            next_topic = Topic.objects.filter(id__gt=author_topic.id,author=author).first()
            #上一篇
            last_topic = Topic.objects.filter(id__lt=author_topic.id,author=author).last()
        else:
            next_topic = Topic.objects.filter(id__gt=author_topic.id,author=author,limit='public').first()
            last_topic = Topic.objects.filter(id__lt=author_topic.id,author=author,limit='public').last()
            print('next_topic的值是:',next_topic)

        #下一篇文章的id和title
        next_id = next_topic.id if next_topic else None
        next_title = next_topic.title if next_topic else ''
        #上一篇文章的id和title
        last_id = last_topic.id if last_topic else None
        last_title = last_topic.title if last_topic else ''

        #关联留言和回复





#查出当前文章的所有留言,相当于拿到了春游的原始数据 all_messages = Message.objects.filter(topic=author_topic).order_by('-created_time') #准备一个数组存留言,准备一个字段存回复 msg_list = [] rep_dic = {} m_count = 0 #判断身份 for msg in all_messages: if msg.parent_message: #回复 #初始化留言字典框架 rep_dic.setdefault(msg.parent_message,[]) rep_dic[msg.parent_message].append({'msg_id':msg.id,'publisher':msg.publisher.nickname,'publisher_avatr':str(msg.publisher.avatar),'content':msg.content,'created_time':msg.created_time.strftime('%Y-%m-%d %H:%M:%S')}) else: #留言 #计数 m_count += 1 msg_list.append({'id':msg.id,'content':msg.content,'publisher':msg.publisher.nickname,'publisher_avatar':str(msg.publisher.avatar),'created_time':msg.created_time.strftime('%Y-%m-%d %H:%M:%S'),'reply':[]}) #关联回复和留言 #判断留言id是否在留言回复里,如果在就证明有留言,就把数据存入到reply里 for m in msg_list: if m['id'] in rep_dic: m['reply'] = rep_dic[m['id']] res = {'code':200,'data':{}} res['data']['nickname'] = author.nickname res['data']['title'] = author_topic.title res['data']['category'] = author_topic.category res['data']['created_time'] = author_topic.create_time.strftime('%Y-%m-%d %H:%M:%S') res['data']['content'] = author_topic.content res['data']['introduce'] = author_topic.introduce res['data']['author'] = author.username res['data']['last_id'] = last_id res['data']['last_title'] = last_title res['data']['next_id'] = next_id res['data']['next_title'] = next_title res['data']['messages'] = msg_list res['data']['messages_count'] = m_count return res

 

标签:author,留言,topic,详情页,res,msg,id,25Django
来源: https://www.cnblogs.com/tyjs09/p/15705639.html