0

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?

Dhanendra
  • 113
  • 4
  • 11

1 Answers1

0

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

Ali Yaman
  • 208
  • 2
  • 10
  • Thanks for answering but I'm looking for a way to return the JSON response based on the custom queryset, It would be awesome if you can suggest a way. – Dhanendra Jan 27 '20 at 05:19