user7804233
user7804233

Reputation:

Update Django object field without refresh the page

How can I call a view function that change object field without refresh the page?

views.py

def add_like(request, pk):
    book = Book.objects.get(pk=pk)
    book.like = True
    book.save()
    return redirect('book_list')

urls.py

url(r'^add_like/(?P<pk>[0-9]+)/$', views.add_like, name='add_like'),

list.html

[...]
<td><a href="{% url 'add_like' pk=book.pk %}" class="btn btn-default"><span class="glyphicon glyphicon-heart" style="color: grey;"></span></a></td>
[...]

Once user click the button, I want to change like status and the tag content to:

<td><a href="{% url 'remove_like' pk=book.pk %}" class="btn btn-default"><span class="glyphicon glyphicon-heart" style="color: red;"></span></a></td>

I know Ajax can be the answer, but I don't know how to implement it.

Thanks.

Upvotes: 5

Views: 2849

Answers (1)

Mauricio Cortazar
Mauricio Cortazar

Reputation: 4213

Instead of

<td><a href="{% url 'remove_like' pk=book.pk %}" class="btn btn-default"><span class="glyphicon glyphicon-heart" style="color: red;"></span></a></td>

Use an input and give it an ID like

<td><input style="color: red" class="book btn btn-default glyphicon glyphicon-heart" value="{book.pk}" /></td>

Then according with this example call the AJAX function

  <script>
    $(".book").on('click', function () {
      var id = $(this).val();

      $.ajax({
        url: '/add_like/',
        data: {
          'pk': id
        },
        dataType: 'json',
        success: function (data) {
          if (data) {
            alert(data);
          }
        }
      });

    });
  </script>

Then update your view with:

from django.http import JsonResponse
def add_like(request):
    pk = request.GET.get('pk', None)
    book = Book.objects.get(pk=pk)
    book.like = True
    book.save()
    data = {'book', book}
    return JsonResponse('data')

Upvotes: 1

Related Questions