Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax POST not sending data when calling 'request.POST' in Django view

I am attempting to get an Ajax POST to to send data to my view so I can manipulate my data there, when I click on a div with class up-arrow.

Problem is, when I click said div and print request.POST in my view file, I am getting a POST object that contains <QueryDict: {}>. Empty! I can't seem to figure out why my the POST request isn't sending my data through.

Here is my HTML...

{% for i in post.posts %}
    <li>
        <div>
            <div class='up-arrow'>
            </div>
            {{i}}
        </div>
    </li>
{% endfor %}

Here is my AJAX/jQuery...

$(document).ready(function(){
            $('.up-arrow').click(function(){
                $(this).hide()
                console.log('click')
                $.ajax({
                    headers: {
                        'Content-Type':'application/json',
                        'X-CSRFToken': getCookie('csrftoken')
                    },
                    url: 'voteuppost',
                    type: 'POST',
                    data: {'dane': 123456789101112},
                    success: function(data) {
                        alert('success!')   
                    },
                    error: function(){
                        alert('fail')
                    }

                })
                return false
            });
            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]);
                    if (cookie.substring(0, name.length + 1) == (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
        })

Here is my view...

class VoteUpPost(View):
    def post(self, request):
        print(request.POST)
        return JsonResponse({'status': True})

Here is my url route...

    url(r'^voteuppost$', VoteUpPost.as_view()),

Things I have tried...

1) I used GET instead of POST and I am able to get the data value using request.GET.get('dane')

1) Tried using request.POST.data and request.POST.DATA and get the following... AttributeError: 'QueryDict' object has no attribute 'data' and I also get a 'fail' alert.

How do I send my data over to my view via a POST request and then access the data within?

like image 871
Erik Åsland Avatar asked Dec 30 '15 15:12

Erik Åsland


2 Answers

When posting JSON data with application/json you need to use request.body instead of request.POST.

Like so:

class VoteUpPost(View):
    def post(self, request):
        print(request.body)
        data = json.loads(request.body)
        return JsonResponse({'status': True})

Also as Jacques mentioned, make sure to update your js to pass a JSON string.

Change:

data: {'dane': 123456789101112},

To:

data: JSON.stringify({'dane': 123456789101112}),
like image 81
Paulo Avatar answered Oct 10 '22 12:10

Paulo


Django request can only parse application/x-www-form-urlencoded and multipart/form-data to request.POST. For other content types you have to use request.body property. for assertion of content type you can get the content type from request.META.get('CONTENT_TYPE')

def sample_view(request):
    if request.META.get('CONTENT-TYPE') == 'application/json':
        data = json.loads(request.body)
        return JsonResponse({'any-message':'Hello'})
like image 28
Navid Nabavi Avatar answered Oct 10 '22 10:10

Navid Nabavi