简体   繁体   English

如何为 api 视图添加 post 方法以便对帖子进行评论?

[英]How do I add a post method for the api view so that posts can be commented on?

I'm building an API using DRF, and as I am a beginner, I can't get my head across this.我正在使用 DRF 构建一个 API,作为初学者,我无法理解这个问题。 I'm building an instagram clone using DRF and was able to attach comments and likes to each post object, but I can only attach likes and comments using the admin panel.我正在使用 DRF 构建一个 Instagram 克隆,并且能够将评论和喜欢附加到每个帖子 object,但我只能使用管理面板附加喜欢和评论。 I can see the total number of likes/comments and the user who added them as JSON Output though.不过,我可以看到喜欢/评论的总数以及添加它们的用户为 JSON Output。 Is there a way to add an add comment_form to the post_detail view?有没有办法向 post_detail 视图添加 add comment_form?

Here's my models.py file这是我的 models.py 文件

from __future__ import unicode_literals
import uuid
from django.db import models
from django.contrib.auth.models import User
from django.conf import settings

# Create your models here.



class Createpost(models.Model):
    id = models.UUIDField(
          primary_key = True,
          default=uuid.uuid4,
          editable= False,
    )
    author = models.ForeignKey(User , on_delete=models.CASCADE)
    title = models.CharField(max_length=50)
    body = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    post_image = models.ImageField(upload_to='images/',blank=True)


    @property
    def total_likes(self):
        return Like.objects.filter(post_id = self.id).count()

    @property
    def likes(self):
        array = []
        for like in Like.objects.filter(post_id = self.id):
            array.append(like.author.username)
        return array
    
    @property
    def total_comments(self):
        return Answers.objects.filter(post_id = self.id).count()

    @property
    def comments(self):
        array = []
        for comment in Answers.objects.filter(post_id = self.id):
            c = {}
            c['body'] = comment.body
            c['username'] = comment.author.username
            c['created_at'] = comment.created_at
            array.append(c)
        return array

    def __str__(self):
        return self.title

class Answers(models.Model):
    post = models.OneToOneField(
        Createpost,
        primary_key=True,
        on_delete = models.CASCADE,
    )
    body = models.TextField()
    author = models.ForeignKey(User,on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)
    Updated_At = models.DateTimeField(auto_now=True)
    active = models.BooleanField(default=False)

    
    def __str__(self):
        return 'Comment {} by {} '.format(self.body,self.author)
class Like(models.Model):
    post = models.OneToOneField(
        Createpost,
        primary_key=True,
        on_delete = models.CASCADE,
    )
    author = models.ForeignKey(User,on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        unique_together = ('post','author',)

Here's my Views.py file:这是我的 Views.py 文件:

from django.shortcuts import render
from rest_framework import generics
from .models import Createpost
from .permissions import IsAuthorOrReadOnly
from .serializers import PostSerializer,PostDetailSerializer,CommentSerializer

# Create your views here.

class PostList(generics.ListCreateAPIView):
    queryset = Createpost.objects.all()
    serializer_class = PostSerializer


class PostDetail(generics.RetrieveUpdateDestroyAPIView):
    permission_classes = (IsAuthorOrReadOnly,)
    queryset = Createpost.objects.all()
    serializer_class = PostDetailSerializer

Here's my serializers.py file:这是我的 serializers.py 文件:

from rest_framework import status
from rest_framework import serializers
from rest_framework.decorators import APIView
from .models import Createpost,Answers
from django.contrib.auth.models import User


class PostSerializer(serializers.ModelSerializer):
    totallikes = serializers.ReadOnlyField(source = 'total_likes')
    totalcomments = serializers.ReadOnlyField(source = 'total_comments')
    class Meta:
        fields = ('id','author','title','body','created_at','totallikes','totalcomments')
        model = Createpost

class CommentSerializer(serializers.Serializer):
    field1 = serializers.CharField()

class PostDetailSerializer(serializers.ModelSerializer):
    li_kes = serializers.ReadOnlyField(source = 'likes')
    com_ments = serializers.ReadOnlyField(source = 'comments')
    
    class Meta:
        fields = ('id','author','title','body','created_at','updated_at','post_image','li_kes','com_ments',)
        model = Createpost

I don't see a comment model in your code, so it's hard to know exactly how you're going about this.我在您的代码中没有看到评论 model,因此很难确切知道您将如何处理。 But one pattern for adding comments to a post object would to create an endpoint that accepts the comment details in the request and saves them to the post.但是向帖子 object 添加评论的一种模式是创建一个端点,该端点接受请求中的评论详细信息并将它们保存到帖子中。 Something like:就像是:

from rest_framework import viewsets, status

class PostComment(viewsets.ModelViewSet):

    """ API endpoint for adding comments to posts """

    def create(self, request):

        Data = request.data
        payload = {'post': Data['post_id'], 'user': self.request.user.id, 'comment': Data['comment']]}
        post = UserPost.objects.get(uniqueID=Data['post_id'])
        payload['post'] = post.id

        serializer = UserCommentReplyPOSTSerializer(data=payload)

        if serializer.is_valid():
            serializer.save()
            return Response('Comment saved', status=status.HTTP_200_OK)
        else:
            print(serializer.errors)
            return Response('There was a problem with your request', status=status.HTTP_400_BAD_REQUEST)

You would then register this endpoint in your urls.py and use it in your front-end comment POST routine.然后,您将在您的urls.py中注册此端点,并在您的前端评论 POST 例程中使用它。

Obviously you'd need a Comment model with a foreign key to to your Post model for this to work.显然,您需要一个 Comment model 和一个指向您的 Post model 的外键才能工作。 I'm assuming you have that and didn't show it.我假设你有那个但没有展示它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 python不提供帖子的网站如何获取post方法? - how do I get the post method for a website that doesn't provide posts in python? "如何防止我的 reddit 机器人评论它已经评论过的帖子?" - How can I prevent my reddit bot from commenting on a post it's already commented on? 发布API-创建代码后需要遵循哪些步骤,以便我可以通过此API将数据添加到txt文件中 - Post API— what are the steps that need to be followed once the code is created so that I can add data into a txt file through this API 当我在视图函数中添加“ POST”作为方法时,该方法是不允许的 - Method is NOT allowed when i add 'POST' as a method in a view function 我正在尝试将帖子添加到帖子表并允许用户能够编辑帖子。 而其他用户可以查看帖子并喜欢它 - im trying to add a post to the posts table and allow the user to be able to edit the post. while other users can view the post and like it 如何修改Wagtail CMS,以便任何用户都可以在自己的博客下发布博客文章 - How to modify wagtail CMS so that any user can post blog posts under their own blog 如何将评论分配给评论过的帖子 - How to assign comment to the post commented on 我可以将我的脚本/api 添加到我的 Django 项目中吗? 如果是这样,我该怎么做 - can I add my script/apis to my Django project? If so how can I do this 我该怎么做才能使他们无法创建超过 300 位数字的帖子? - How can I do so that they cannot create a post with more than 300 digits? 如何在API视图中执行更多操作? - How can I do more things in the API View?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM