我想在Django-Rest-Fram中创建一个评论功能。

2024-09-27 22:27:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在django rest框架中创建一个注释函数 这是我的职责视图.py在

def postdetail(request,id):
   postt = get_object_or_404(post,id=id)
   comments = Comment.objects.filter(post=postt,reply=None).order_by('-id')
   is_liked = False
   if postt.like.filter(id=request.user.id).exists():
       is_liked = True
   if request.method == 'POST':
       comment_form = CommentForm(request.POST or None)
       if comment_form.is_valid():
          content = request.POST.get('content')
          reply_id = request.POST.get('comment_id')
          comment_qs = None
          if reply_id:
             comment_qs = Comment.objects.get(id=reply_id)
          comment =  Comment.objects.create(post=postt,user=request.user,content=content,reply=comment_qs)
        comment.save()

        # return HttpResponseRedirect(postt.get_absolute_url())
    else:
       comment_form = CommentForm()

context = {
  'post': postt,
  'is_liked': is_liked,
  'total_likes':postt.total_likes(),
  'comments':comments,
  'comment_form':comment_form,
}
if request.is_ajax():
    html = render_to_string('comments.html',context,request=request)
    return JsonResponse({'form':html})

return render(request,'detail.html', context)

在模型.py在

^{pr2}$

我想在django rest框架中创建一个注释函数链接post帮助我?在


Tags: formidgetifisrequesthtmlcomment
1条回答
网友
1楼 · 发布于 2024-09-27 22:27:26

对注释模型使用模型序列化程序。在

例如

from rest_framework import serializers, generics

class CommentSerializer(serializers.ModelSerializer):
    class Meta:
         model = Comment
         fields = ... # fields you'd like to include

''' API Endpoints '''
class CommentCreate(generics.CreateAPIView):
     queryset = Comment.objects.all()
     serializer_class = CommentSerializer

您可以将这些类附加到一个url,然后发布一些包含post id和user id等的数据。例如:

^{pr2}$

参见:docs

相关问题 更多 >

    热门问题