4
votes

Im kind of new to Django Rest Framework. I know it is possible to post data using the Browsable API, I just don't know how. I have this simple view:

class ProcessBill(APIView):

    def post(self, request):

        bill_data = request.data
        print(bill_data)

        return Response("just a test", status=status.HTTP_200_OK)

When I go to the url that points to this view, I get the rest_framework browsable api view with the response from the server method not allowed which is understandable cause I am not setting a def get() method. But ... how can I POST the data? I was expecting a form of some kind somewhere.

EDIT This is a screenshot of how the browsable API looks for me, it is in spanish. The view is the same I wrote above but in spanish. As you can see ... no form for POST data :/ .

enter image description here

2
You must be seeing a text box below labeled as - Content. Can you share screenshot of how your browser window looks like? - Rohit Jain
@RohitJain Thans for the answer. Just added it as an edit. - Alejandro Veintimilla
You need to define a get_serializer_class() method or serializer_class attribute in your view. - Rohit Jain
@RohitJain Did that but it doesn't work. Also, it doesn't make much sense that it would solve it. Could you point me to the docs, I've tried to find info about "setting up" the Browsable Api but coulnd't find any. Looks like it is supposed to work out of the box. - Alejandro Veintimilla
@alejoss I think that your post method needs to accept the format kwarg, but posting should generally work as far as I know. Have you tried to POST some data from command line (i.e. using curl?) to see if the server accepts it? - Geotob

2 Answers

3
votes

Since you are new I will recommend you to use Generic views, it will save you lot of time and make your life easier:

class ProcessBillListCreateApiView(generics.ListCreateAPIView):
    model = ProcessBill
    queryset = ProcessBill.objects.all()
    serializer_class = ProcessBillSerializer

    def create(self, request, *args, **kwargs):
        bill_data = request.data
        print(bill_data)
        return bill_data

I will recommend to go also through DRF Tutorial to the different way to implement your endpoint and some advanced feature like Generic views, Permessions, etc.

0
votes

Most likely the user has read-only permission. If this is the case make sure the user is properly authenticated or remove the configuration from the projects settings.py if it is not necessary as shown below.

    ```#'DEFAULT_PERMISSION_CLASSES': [
       # 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
       #],```

Read more on permissions here.