在Django Rest框架中返回对成功POST请求的自定义响应 [英] Return custom response to successful POST request in django rest framework
问题描述
当用户使用POST请求访问API时,我想向用户返回自定义响应,并且成功.以下是代码片段: views.py
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?
推荐答案
您可以在views.py上编写自定义api.我想举例;
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})
然后定义网址.
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'),
]
就是这样.
您还可以管理渗透:https://www.django-rest-framework.org/api-guide/permissions/#setting-the-permission-policy 并且您可以在视图上使用序列化程序: https://www.django-rest-framework.org/api-guide/serializers/#saving-instances
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
这篇关于在Django Rest框架中返回对成功POST请求的自定义响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!