问题
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