user1050619
user1050619

Reputation: 20906

DJango rest framework createapiview

Im using Django rest framework CreateAPIView to create some data and here is the view.

class CompanyCreateApiView(CreateAPIView):

    def post(self, request, *args, **kwargs):
        print 'request ==', request
        for each in args:
            print 'args ==', each
        for each in kwargs:
            print 'keargs ==', each
        import json
        data=json.dumps({'status':'success'})
        return Response(data, status=status.HTTP_200_OK)

now I call this viewset using python request module and don't see post data being printed in *Args or **kwargs parameter

**

import requests
r = requests.post('http://127.0.0.1:8000/api/create-company-profile/',data={'key':'value'})
print r.status_code
print r.text

**

Upvotes: 2

Views: 5463

Answers (2)

Dhia
Dhia

Reputation: 10619

You don't see any response because they are empty, it's like

for item in []:
   print item

it can't iterate over empty data, but in case you send a value in the url:

url(r'^/api/create-company-profile/(?P<name>\w+)/$', CompanyCreateApiView.as_view()),

kwargs will have the following value {"name": comany_name}

in order to retrieve the data send in the body of the request you use request.data, you may find also some example in the internet such as request.DATA or request.QUERY_PARAMS, but it's deprecated in the newer version of django and replaced by request.data

Upvotes: 0

Joey Wilhelm
Joey Wilhelm

Reputation: 5819

You won't see any POST data in those; instead, you will see it in request.data. As described in the django-rest-framework documentation:

request.data returns the parsed content of the request body. This is similar to the standard request.POST and request.FILES attributes except that:

  • It includes all parsed content, including file and non-file inputs.
  • It supports parsing the content of HTTP methods other than POST, meaning that you can access the content of PUT and PATCH requests.
  • It supports REST framework's flexible request parsing, rather than just supporting form data. For example you can handle incoming JSON data in the same way that you handle incoming form data.

Upvotes: 3

Related Questions