skip to Main Content

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.

2

Answers


  1. As you can see in your request there is not data passed to the api. You may want to use POST request to send data. GET method does not accept data parameter.

    Login or Signup to reply.
  2. Try this as Igor Moraru suggest, using post:
    
    
    # Python
    
    def post_details(request):
        if request.method == 'POST' and request.is_ajax:
    
            post_id = request.POST.get('post_id')
    
            data = GetPostDetails(post_id)
            data = json.dumps(str(data))
            return JsonResponse(data, safe=False)
    
    
    
    
    // Java script
    
    
    $(document).on('click', '#post-det', function(e) {
    
        e.preventDefault();
    
        var post_id = $(this).children(':first-child').text();
        var post_id = parseInt(post_id);
    
        $.ajax({
              type: "POST",
              url: "{% url 'get_post_details' %}",
              dataType: "json",
              data: {
                  "post_id": post_id
              },
              success: function(data) {
                 console.log(data);
              }
          });
    
    });
    
    // Send the csrftoken
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    
    var csrftoken = getCookie('csrftoken');
    
    function csrfSafeMethod(method) {
        // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }
    
    $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            }
        }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search