First, create a likes app and add it to your INSTALLED_APPS (and to your app's volumes in docker-compose.yml if you are using Docker). Then, set up a Like model, which has a foreign-key relation to the user who is liking something and a generic relationship to any object in the database. We will use ObjectRelationMixin, which we defined in the Creating a model mixin to handle generic relations recipe in Chapter 2, Database Structure and Modeling. If you don't want to use the mixin, you can also define a generic relation in the following model yourself:
# likes/models.py from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from utils.models import (CreationModificationDateMixin,
object_relation_mixin_factory)
class Like(CreationModificationDateMixin,
object_relation_mixin_factory(is_required=True)):
class Meta:
verbose_name = _("like")
verbose_name_plural = _("likes")
ordering = ("-created",)
user = models.ForeignKey(settings.AUTH_USER_MODEL)
def __str__(self):
return _(u"%(user)s likes %(obj)s") % {
"user": self.user,
"obj": self.content_object,
}
Also, make sure that the request context processor is set in the settings. We also need an authentication middleware in the settings for the currently logged-in user to be attached to the request:
# settings.py or config/base.py
MIDDLEWARE = [
# ...
'django.contrib.auth.middleware.AuthenticationMiddleware',
]
TEMPLATES = [
{
# ...
'OPTIONS': {
'context_processors': [
# ...
'django.template.context_processors.request',
],
},
},
]
Remember to create and run a migration to set up the database accordingly for the new Like model.