I want to send data via Ajax to my Django Server. But when I want to read these data I get a bad request error back. I dont know why, other methods like request.method or request.stream work well.
This is the Ajax Call:
jQuery.ajax({
type: 'post',
url: 'http://127.0.0.1:8000/termin/get-journey-time/',
contentType: 'application/json; charset=utf-8',
data: {
'method': 'get_journey_time',
'mandant_id': 1,
'customer_address': customer_address,
'staff_group': staff_group_id
},
success: function (resultData) {
console.log(resultData)
});
This is my view for this post request:
class get_journey_time(generics.ListAPIView):
"""
Handle Ajax Post to calculate the journey time to customer for the selected staff group
"""
permission_classes = (AllowAny,)
def post(self, request, *args, **kwargs):
body = request.data
return Response(body)
I get error code 400 Bad Request. Do you know why?
def post(self, request, *args, **kwargs):
body = request.method
return Response(body)
or
def post(self, request, *args, **kwargs):
body = request.stream
return Response(body)
Work well
You are getting HTTP 400 because your code is raising an exception. Since other methods work, it must be the body = request.data
part. After reading the docs I assume there must be something wrong with parsing the data you are POSTing. Like, isn't serializer needed here?
I found my mistake.
After reading the django rest framework documentation I figured out that I have called the wrong parameters in the post method.
def post(self, request, format=None):
instead of def post(self, request, *args, **kwargs)
worked for me. Thanx all, best!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.