我想在django-rest-framework中创建评论功能 这是我在views.py
中的功能fun <THING: [OneThing, ASimilarThing]> process(thing: THING) { ... }
models.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)
我想在django-rest-framework中创建评论功能,以将帖子链接到我吗?
答案 0 :(得分:0)
为您的评论模型使用模型序列化器。
例如
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,然后发布一些包含帖子ID和用户ID等的数据。例如:
curl -X POST -d '{ SOME DATA }' http://localhost:8000/api/....
请参阅:docs