How to do it...

Execute these steps one by one:

  1. In the likes app, create a templatetags directory with an empty __init__.py file to make it a Python module. Then, add the likes_tags.py file, where we'll define the {% like_widget %} template tag as follows:
# likes/templatetags/likes_tags.pyfrom django import templatefrom django.contrib.contenttypes.models import ContentTypefrom django.template.loader import render_to_stringfrom likes.models import Likeregister = template.Library()class ObjectLikeWidget(template.Node):    def __init__(self, var):        self.var = var    def render(self, context):        liked_object = self.var.resolve(context)        ct = ContentType.objects.get_for_model(liked_object)        user = context["request"].user if not user.is_authenticated: ...

Get Django 2 Web Development Cookbook - Third Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.