title: How to implement a like system in Django templates
body: <p>I am currently working on building a &quot;like&quot; system for a blog-style website in Django.  I've been looking at several different examples for setting up the HTML templates and was hoping to better understand some of the logic.</p>
  <p>My first thought was to tie the &quot;like&quot; button to the corresponding view like so:</p>
  <pre><code>&lt;a class=&quot;btn btn-secondary&quot; href=&quot;{% url 'post-like' post.id %}&quot; role=&quot;button&quot;&gt;Like ({{ post.likes.count }})&lt;/a&gt;
  </code></pre>
  <p>This seemed to work decently well (the &quot;like&quot; was registering and showing up in the count) but I was having trouble getting back to the right page after clicking the &quot;like&quot; button (i.e. when I clicked &quot;like&quot; it took me to some other page vs. staying on the home page).</p>
  <p>I then found another example online that created a <code>get_like_url()</code> function under the broader <code>Post</code> <code>Model</code> like this:</p>
  <pre><code>def get_like_url(self):
          return reverse(&quot;post-like&quot;, kwargs={&quot;pk&quot;:self.id})
  </code></pre>
  <p>And then called it in the template like this:</p>
  <pre><code>&lt;a class=&quot;btn btn-secondary&quot; href=&quot;{{ instance.get_like_url }}&quot; role=&quot;button&quot;&gt;Like ({{ post.likes.count }})&lt;/a&gt;
  </code></pre>
  <p>I thought this was basically doing the same thing but when I used this method it would return me to the home page of my site but wouldn't register the like (i.e. didn't seem like the button actually did anything).</p>
  <p>Could anyone help me understand what is going on here?</p>
  <p>For reference, here is my <code>View</code> for the &quot;like&quot; system:</p>
  <pre><code>class LikeView(View):
      model = Post
      context_object_name = 'posts'
  
      def get(self, request, pk=None):
          user = self.request.user
          post = Post.objects.get(pk=pk)
          updated = False
          liked = False
          if user.is_authenticated:
              if user in post.likes.all():
                  liked = False
                  post.likes.remove(user)
              else:
                  liked = True
                  post.likes.add(user)
              updated = True
          data = {
              &quot;updated&quot;: updated,
              &quot;liked&quot;: liked,
          }
          return HttpResponse(data)
  </code></pre>
  <p>And my <code>URL pattern</code>:</p>
  <pre><code>path('post/like/&lt;int:pk&gt;', LikeView.as_view(), name='post-like')
  </code></pre>
  <p>Thanks in advance for the help!</p>