大家好,我想为DRF中的帖子创建一个喜欢的功能
Creating a "like" url/button for Django Rest Framework
我从堆栈溢出中遵循了上述问题
这是我的模型。py
class status(models.Model):
user=models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, null=False)
# user=models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
content=models.TextField(blank=True,null=True)
image=models.ImageField(upload_to="upload",null=True,blank=True)
updated=models.DateTimeField(auto_now=True)
time=models.DateTimeField(auto_now_add=True)
likes=models.ManyToManyField(settings.AUTH_USER_MODEL,blank=True,related_name='post_likes')
def __str__(self):
return self.content
serializers.py
class statusSerializer(serializers.ModelSerializer):
# user_name = serializers.ReadOnlyField(source='user.username')
user=UserPublicSerializer(read_only=True)
# rating=RatingSerializer(required=False)
# rating=RatingSerializer()
class Meta:
model=status
fields=['id','user','content','image','likes']
views.py
@api_view(['POST'])
def LikesApi(self,request,id):
# status = get_object_or_404(id=request.POST.get('id', ''))
status = get_object_or_404(id=id)
status.likes.add(request.user)
serializer = statusSerializer(status)
return Response(serializer.data, status=status.HTTP_201_CREATED)
我已经尝试过从堆栈上考虑该问题的两种方式
@api_view(['POST'])
def LikesApi(self,request,id):
serializer=statusSerializer(data=request.DATA)
if serializer.is_valid():
serializer.object.content_object=get_object_or_404(status,id=request.POST.get('id', ''))
serializer.object.likes.add(request.user)
serializer.save()
return RestResponse(serializer.data, status=status.HTTP_201_CREATED)
return RestResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
这是我的urls.py
urlpatterns = [
# url(r'^$/', StatusListSearchApi.as_view()),
url(r'^list/', StatusListSearchApi.as_view()),
url(r'^user/', UserPost.as_view()),
url(r'^like/(?P<id>\d+)/$',LikesApi),
post对象存在于我的api / list / url
http://127.0.0.1:8000/api/list/like?id=35
当我触发此网址时,我无法在可浏览的api detailview中看到喜欢的增加
http://127.0.0.1:8000/api/like?id=35
也尝试过此操作,但页面未找到404错误
我不知道问题出在哪里,我该如何通过网址获取特定帖子的ID并处理视图
答案 0 :(得分:0)
我建议您使其成为RESTful,并使其网址类似:/api/status/<status_id>/like
,
还可以查看naming conventions并为您修改姓名。
对于视图,这将是处理的好方法:
from django.shortcuts import get_object_or_404
from rest_framework.response import Response
from <your_package>.models import YourStatusModel
@api_view(['POST'])
def like_api_view(self, request, status_id):
obj = get_object_or_404(YourStatusModel.objects.all(), id=status_id)
obj.likes.add(request.user)
return Response(status=status.HTTP_201_CREATED)