Like/Unlike Button with jQuery in a Django App

March 13, 2018, at 5:39 PM

I'm trying to create a Like/Unlike button with jQuery! Here's what I did,

Here's the HTML,

<span class="like-button">{% if request.user in content.likes.all %}Unlike{% else %}Like{% endif %}</span>

Here's the jQuery,

    var x = $(this);
    } else {

This code seems working fine but the problem is when i like some content (it shows Unlike, fine) & then refresh the page (still shows Unlike, fine), But when I press Unlike after refreshing page it doesn't work. It takes 2 clicks not 1 to change from Unlike to Like.

Answer 1

You'll need to construct a Django view and model to accept the AJAX "like" event.

As hansTheFranz pointed out, you aren't saving the like/unlike to anything on the back end.

This is what the typical ajax + Django pattern looks like:

jQuery "like" > Url > View > Model

Here's a typically constructed jQuery ajax handler:

You'll have to fill in some things...

$(".like-button").click(function( event ) {
  // Getting the thing they "liked"
  var post_id = $('#post_id').val()
  // Making the ajax call...
    url: 'like', // This url is defined in Django
    type: 'POST',
    data: {
      //put any data vars you want to capture here
      'post_id': post_id
    success: function (json) {
      // When the ajax call is successful, what do you want?
      // Usually this is where you update UI elements, etc.
    error: function (xhr,errmsg,err) {

Next is our Django URL in

urlpatterns = [
  path('like',, name='like'),

So, you click the like button, that fires and AJAX POST request at '/like' url. Django routes that request to a view named 'like'.

A simple view in

from myapp.models import Post
def like(request):
  # Save the like to the database
  post = Post.objects.get(pk = request.POST['post_id']
  post.number_of_likes += 1
  data = []
  data['post_likes'] = post.number_of_likes
  return JsonResponse(data)

In the above view, I've pulled in the model of a 'Post' and accessed the post instance that the user liked. Then I added 1 like to the post's total and saved it. Finally I return the total number of likes on the post back to the jQuery ajax call as a JsonResponse. This way, I can update my original Ajax success function to show the user that their like was saved and incremented the like total.

Here's a quick example of the Post model:

from django.db import models
class Post(models.model):
  id = models.IntegerField(pk = True)
  number_of_likes = models.IntegerField()

So to recap, we built a simple Ajax > View > Model pattern, where every time the like button is clicked the Post model object is incremented by one. Don't confuse the Post model object with the POST request type. I just chose the name Post as an example, it could also be a Person, Tree, etc. Each of these three steps in the above example are extensible, meaning you can add more code to each piece to produce different results. I'd recommend playing around with this pattern to find a best fit for your application.

Final note: You'll want to study up and use Cross Site Request Forgery if you want your application to be secure. Without it, a malicious user could alter the above ajax request to do all kinds of nasty things to your database. I'm leaving implementation of that as an exercise to the reader.

&lt;input type="file&gt; limit selectable files by name

<input type="file> limit selectable files by name

I want to make an upload table where each file has its own upload ButtonTo make it easier for user i want to restrict the choosable files by name similar to how the accept tag limits the type

Jquery .slice chars from array?

Jquery .slice chars from array?

obj is a array that contains youtube linksIt includes around 32 youtube links if you are at youtube

Sending changes to a sql Database without refreshing the page core 2.0

Sending changes to a sql Database without refreshing the page core 2.0

I have a bunch of draggable divs and i need to save their positions in a sql database when they are dropped, but i dont want it to refresh the pageIm thinking of adding some ajax call when the div is dropped but i have no idea what that ajax call would look like

Using math.random for A/B testing

Using math.random for A/B testing

Currently I have setup a piece of code to use for A/B testing based on 50/50But now I want to rebuild it to a 50/25/25 setup