I have been working on a Django REST API and one of the views is as follows :
@api_view(['POST'])
def create(request):
key = request.POST.get('key')
name = request.POST.get("name")
email = request.POST.get("email")
password = request.POST.get("password")
print(key)
if(key=='0'):
user = Users(name=name,email=email,password=password)
user.save()
return Response("User Created Successfully")
else:
return Response("Invalid Key")
When I send a POST request with all the proper parameters I get the key printed as NONE, but I tried replacing POST with GET every where as below and then sending a GET request actually works normally, but POST request isn't working :
@api_view(['GET'])
def create(request):
key = request.GET.get('key')
name = request.GET.get("name")
email = request.GET.get("email")
password = request.GET.get("password")
print(key)
if(key=='0'):
user = Users(name=name,email=email,password=password)
user.save()
return Response("User Created Successfully")
else:
return Response("Invalid Key")
Thanks in advance !!
Tried GET instead of POST and that works, but since this is a method to enter value in the DB so this should be POST request.
[Edit 1]
I have tried using request.data but that isn't working, it is returning empty request like this {} and the same is the case with request.POST.
I am sending the request from Postman. The request I am sending is like this :
CodePudding user response:
In your screenshot, you are passing query parameters in POST
request. You should POST
data though data tab in postman (formdata,json,etc). Based on your screenshot, you can get the data passed through request.query_params
, but this is not recommended for POST
requests.
In Django REST Framework, request.POST
or data submitted through POST
is restructured into request.data
and data through GET
requests is passed into request.query_params
. Both of these are QueryDict
, so normal dictionary methods are applicable.
Reference: https://www.django-rest-framework.org/api-guide/requests/#request-parsing