I have an AJAX request to pull some data from post model"I am using Django3 and python 3.8". When I print the request.GET.get to the console, I got "None". There was no Data. However, when I alert the passed data in javascript I got the right value. I could not figure out which portion of my code should be tweak a little bit to work.
Here is the AJAX call:
<script type="text/javascript">
// to submit the get request and prevent the default submission
$(document).on('click', '#post-det', function(e) {
e.preventDefault();
var post_id = $(this).children(':first-child').text();
var post_id = parseInt(post_id);
alert(post_id);
$.ajax({
'type':'GET',
'url': "{% url 'get_post_details' %}",
'data':post_id,
'processData': false,
'cache':false,
'contentType': false,
'dataType': 'json',
csrfmiddlewaretoken:'{{ csrf_token }}',
success: function(data) {
alert(data)
},
});
});
</script>
I got "2" for the post_ID
However, I could not retrieve it in Django view function. Here is the view function:
def post_details(request):
if request.method == 'GET' and request.is_ajax:
post_id = request.GET.get('data')
print("this is to check if the post_id is passed", post_id)
print(request.GET.get)
data = GetPostDetails(post_id)
data = json.dumps(str(data))
return JsonResponse(data, safe=False)
return JsonResponse({"error": "there was an error"}, status=status.HTTP_400_BAD_REQUEST)
The print function print this line.
this is to check if the post_id is passed None
<bound method MultiValueDict.get of <QueryDict: {'_': ['2345678976543']}>>
[04/May/2020 08:22:21] "GET /post/Post_details/?_=2345678976543 HTTP/1.1" 200 8
Also, this is the request header:
Request URL: // I removed it
Request Method: GET
Status Code: 200 OK
Remote Address: 127.0.0.1:8000
Referrer Policy: no-referrer-when-downgrade
Response Headersview source
Content-Length: 8
Content-Type: application/json
Date: Mon, 04 May 2020 08:06:50 GMT
Server: WSGIServer/0.2 CPython/3.8.2
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
Request Headersview source
Accept: application/json, text/javascript, */*; q=0.01
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Cookie: //I removed it//
Host: 127.0.0.1:8000
Referer: http://127.0.0.1:8000/ // I removed it
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-origin
User-Agent: // I removed it
X-Requested-With: XMLHttpRequest
NOTE: I did not have any error message but the json return empty object and when I hard coded the post_id and make it post_it = 1 . I have the object with all post details.
Your advice and guidance is highly appreciated.
print(request.body)?