How to add Tags to Your Django Models?

Django development

django-taggit is a reusable application that primarily offers you a Tag model, and a manager for easily adding tags to any model. We will create very simple blog app and implement tagging system in it.

I am assuming that you already created Django project. Let’s Start with installing package by following command:

pip3 install django-taggit

Once its installed, open and include taggit in your INSTALLED_APPS


Create Model

Now, open and create Product model:

from django.db import models
from django.utils.text import slugify
from django.shortcuts import reverse
from taggit.managers import TaggableManager

class Product(models.Model):
    slug=models.SlugField(max_length=225, unique=True)
    subcategory=models.ForeignKey('SubCategory', related_name='prosubcat', on_delete=models.CASCADE, blank=True, null=True)
    saleprice = models.IntegerField()
    description = models.TextField()
    overview = models.TextField(null=True)
    featured = models.BooleanField(null=True)
    tags = TaggableManager()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):

    def save(self,*args, **kwargs):
        self.slug = slugify(
        #unique_slugify(self, cat_slug_str)
        super(Product, self).save(*args, **kwargs)

Create Form

In your

from django import forms
from .models import Product

class ProductForm(forms.ModelForm):
    class Meta:

Create Views

Let’s see

from django.shortcuts import render, get_object_or_404
from django.template.defaultfilters import slugify

from .models import Product
from .forms import ProductForm
from taggit.models import Tag

def create_product(request):
   common_tags = Product.tags.most_common()[:4]
   form = ProductForm(request.POST)
 if form.is_valid():
   newpost =
   newpost.slug = slugify(
 'subcat':subcat, 'common_tags':common_tags, 'form':form,
 return render(request, 'yourpage.html', context)
def detail_view(request, slug):
    post = get_object_or_404(Post, slug=slug)
    context = {
    return render(request, 'detail.html', context)
def tagged(request, slug):
    tag = get_object_or_404(Tag, slug=slug)
    # Filter posts by tag name  
    posts = Post.objects.filter(tags=tag)
    context = {
    return render(request, 'home.html', context)

When saving a form, you have to use the commit=False option and call save_m2m() on the form after you save the object.

We are using slugify to convert our post title (string) to valid slug.

As you see you can filter posts by tag name and display most used tags.

Create Template

Great! Now we can create our templates.

<p>Common Tags: 
            {% for mt in common_tags %}
                <a href="#" class="badge badge-success">{{mt}}</a>
            {% endfor %}
Database Table of Django-taggit package
Tag name with slug
Output of Django-taggit