Django REST Framework不在Browsable API中生成表单

时间:2015-12-17 20:26:34

标签: django django-rest-framework

好的,我有一个GenericAPIView应该在Browsable API中生成一个表单,因为它声明了post方法:

from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response

from transacciones.serializers import BillSerializer


class ProcessBill(GenericAPIView):

    serializer_class = BillSerializer

    def post(self, request):

        recieved_data = request.data

        print(recieved_data)

        return Response("Processed Bill", status=status.HTTP_200_OK)

但它不会生成表格。视图看起来像这样(它是西班牙语,我将代码翻译成英语,因此阅读起来更加舒适):

enter image description here

我知道我得到405 Method not Allowed因为我没有定义get方法,只定义post

我使用Django 1.8,Django REST Framework 3.3.1和python 3.4。我迷失在这里。有任何想法吗?

修改

另外,如果我使用Postman(Chrome添加),视图会正确响应。

4 个答案:

答案 0 :(得分:1)

您可以使用此

from rest_framework.generics import CreateAPIView
from rest_framework.mixins import CreateModelMixin
from rest_framework.response import Response

from transacciones.serializers import BillSerializer


class ProcessBill(CreateModelMixin, GenericAPIView):
    serializer_class = BillSerializer

    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)

    def create(self, request, *args, **kwargs):
        # Do whatever you want here

        # Then invoke the create method and create your instance
        return super().create(request, *args, **kwargs)

或者作为替代方案,您只需继承CreateAPIView,它与上面的代码基本相同:)

答案 1 :(得分:1)

如果您使用generics.RetrieveUpdateDestroyAPIView,则必须定义可以自定义的permission_classes。

class ObjectDetail(generics.RetrieveUpdateDestroyAPIView):
    """
    Object RUD (Read Update Delete) API
    """
    permission_classes = ( checkUserPermission, )
    queryset = Object.objects.all()
    serializer_class = ObjectSerializer

或者如果您只想对此进行测试,请使用permission_classes = ( AllowAny, )

class ObjectDetail(generics.RetrieveUpdateDestroyAPIView):
    """
    Object RUD (Read Update Delete) API
    """
    permission_classes = ( AllowAny, )
    queryset = Object.objects.all()
    serializer_class = ObjectSerializer

答案 2 :(得分:0)

我遇到了同样的问题,邮递员看到这是一个凭据问题,因此将当前用户状态更改为员工解决了问题。

答案 3 :(得分:0)

我遇到了同样的问题。就我而言,错误出在串行器中,在此我使用django.db.models.CharField(...)而不是rest_framework.serializers.CharField(...)