Return custom response to successful POST request in django rest framework

眉间皱痕 提交于 2021-02-11 14:56:42

问题


I want to return a custom response to the user when they hit the API with a POST request and it's a success. Here are the code snippets : views.py

class BlogPostAPIView(mixins.CreateModelMixin,generics.ListAPIView):
    # lookup_field = 'pk'
    serializer_class = BlogPostSerializer
    def get_queryset(self):
        return BlogPost.objects.all()
    def perform_create(self, serializer):
        serializer.save(user=self.request.user)
    def post(self,request,*args,**kwargs):
        return self.create(request,*args,**kwargs)

urls.py

app_name = 'postings'
urlpatterns = [
    re_path('^$', BlogPostAPIView.as_view(),name='post-create'),
    re_path('^(?P<pk>\d+)/$', BlogPostRudView.as_view(),name='post-rud'),
]

Right now it's returning the details of the post request as successful response, is there any way I can return some other response based on my own custom queryset?


回答1:


You can write custom api on views.py. I want to for example;

from rest_framework.views import APIView 
from rest_framework.response import Response


class Hello(APIView):
    @csrf_exempt
    def post(self, request):
        content = "Hi"
        type = "message" 
        return Reponse({"content":content,"type":type})

and than define url.

app_name = 'postings'
urlpatterns = [
    re_path('^$', BlogPostAPIView.as_view(),name='post-create'),
    re_path('^(?P<pk>\d+)/$', BlogPostRudView.as_view(),name='post-rud'),
    re_path('^hello/$', Hello.as_view(),name='Hello'),
]

That's it.

Also you can manage permessions : https://www.django-rest-framework.org/api-guide/permissions/#setting-the-permission-policy and you can use serializer on views : https://www.django-rest-framework.org/api-guide/serializers/#saving-instances



来源:https://stackoverflow.com/questions/59913388/return-custom-response-to-successful-post-request-in-django-rest-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!