Skip to content

django using ajax to call backend has problem

I’m new to Django. I want to create liking icon for my blog post. here is a heart icon in my html file, and I want when I click it, it turns to red and then calls a function in backend to change a number in database and send back the new number to the template, all using Ajax, in order not to refreshing the page after liking the post. What should I do, and where is the problem?

In html file:

  <i class="fas fa-heart"></i>
  <b>{{ note.like }}</b>

The script part:

  <script>
    $(document).ready(function() {
        $('.fa-heart').click(function(e){
            this.style.color = this.style.color == 'red' ? 'white' : 'red';
            e.preventDefault();

                $.ajax({
                    type:'POST',
                    url:"vote/like/",
                    data:{
                        num:"niloofar",
                        //I think the problem is with this csrf token part
                        csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),
                    },
                    success: function(data){
                        alert(data);
                    },
                    error : function() {
                        console.log("Error");
                    }
                });
        });
    });
  </script>

In views:

  def like(request):
      if request.method == 'POST':
        print(request.POST)
        return HttpResponse('done')

In urls.py:

  path('<int:id>/vote/like/', views.like, name='like'),

And the error is:

Internal Server Error: /notes/1/vote/like/ Traceback (most recent call last): File “/home/niloofar/git/djangoenv/lib/python3.9/site-packages/django/core/handlers/exception.py”, line 47, in inner response = get_response(request) File “/home/niloofar/git/djangoenv/lib/python3.9/site-packages/django/core/handlers/base.py”, line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) TypeError: like() got an unexpected keyword argument ‘id’

Answer

A request to /1/vote/like/ would match the URL <int:id>/vote/like/ in the list and Django would call the function views.like(request, id=1) but your function only accept single argument which is request hence the error.

Change your function like to something like below then it should work fine.

def like(request, id):
    ...

OR

def like(request, *args, **kwargs):
    ...