Python Django Tags System Example Tutorial

Published On: 16/08/2022 | Category: Django

Hi Dev,

Now, let's see post of python django tags system example tutorial. We will look at example of how to add tags to your models in django. I would like to share with you adding tags using django-taggit in django. We will use python django tags system example. Let's see bellow example django bootstrap tag system.

Sometimes,you find a blog categories and tags wise help you organize your web site or blog and help your users find the information they want. A blog category is a topic you address on your blog. Your category list is like the table of contents for your blog.By tagging an article with relevant key words, user can find the information easily so it makes your blog more professional.

Basically 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.

You can use these examples with django3 (django 3) version.

let's see below simple example with output:

Step 1: Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject example
Step 2: Create a App
python3 startapp core
Step 3: Install django-taggit Library

In this step let's start with installing package by following command:

pip install django-taggit
Step 4: Update

Here, do not forget to register the new app in the file. just add ‘core’ to the list and another is include taggit in your INSTALLED_APPS.

Step 5: Create a Model

In this step we will require the database model for storing post and tags.Open the core/ file and add the following code:

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

class Post(models.Model):
    title = models.CharField(max_length=250)
    description = models.TextField()
    published = models.DateField(auto_now_add=True)
    slug = models.SlugField(unique=True, max_length=100)
    tags = TaggableManager()

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        self.slug = slugify(self.title, allow_unicode=True)
        super().save(*args, **kwargs)

        for tag in self.tags.all():
            tag_dict,_ = Tag.objects.get_or_create(tag=str(tag))
            tag_dict.count += 1

class Tag(models.Model):
    tag = models.CharField(max_length=100)
    slug = models.SlugField(unique=True, max_length=100)
    count = models.IntegerField(default=0)

    def __str__(self):
        return self.tag

    def save(self, *args, **kwargs):
        self.slug = slugify(self.tag, allow_unicode=True)
        super().save(*args, **kwargs)

Next, you need to migrate your database using the following command:

python makemigrations
python migrate
Step 6: Create a Form

In this step We need to create a form that will be used .like add a bootstrap class and validation etc.. plus we need to add custom styling.

from django import forms
from .models import Post

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = [
Step 7: Creating the Views

In this step, we need to create the views for performing ajax image upload to the database.Open the core/ file and add.

from django.shortcuts import render, get_object_or_404
from django.template.defaultfilters import slugify
from .models import Post,Tag
from .forms import PostForm

# Create your views here.
def home_view(request):
    posts = Post.objects.order_by('-published')
    # Show most common tags 
    form = PostForm(request.POST)
    if form.is_valid():
        newpost =
        newpost.slug = slugify(newpost.title)
        # Without this next line the tags won't be saved.
    context = {
    return render(request, 'home.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 = Tag.objects.filter(slug=slug).values_list('tag', flat=True)
    posts = Post.objects.filter(tags__name__in=tag)

    return render(request, 'home.html', { 'posts': posts,'tag':tag,'slug':slug })
Step 8: Creating the Templates

So, finally we are here to this step we need to creating django templates following below file:

Next, open the core/templates/base.html file and the add:

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <link rel="stylesheet" href="">
        <link rel="stylesheet" href="" />
        .bootstrap-tagsinput .tag{
            margin-right: 2px;
            color: #ffffff;
            background: #2196f3;
            padding: 3px 7px;
            border-radius: 3px;
        .bootstrap-tagsinput {
            width: 100%;

    {% block content %}{% endblock content %}
    <script src=""></script>
    <script src=""></script>
    <script src=""></script>
    <script src=""></script>

Next, open the core/templates/home.html file and the add:

{% extends 'base.html' %}

{% block content %}
    <div class="container pt-5">
        <div class="row d-flex justify-content-center">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        <h3>Python Django Tags System Example Tutorial - <span class="text-primary"></span></h3>
                    <div class="card-body">
                        <form method="POST">
                            {% csrf_token %}
                            <div class="mb-3">
                                <input type="text" class="form-control" name="title" placeholder="Add title">
                            <div class="mb-3">
                                <textarea type="text" class="form-control" name="description" placeholder="Add description"></textarea>
                            <div class="mb-3">
                                <input type="text" data-role="tagsinput" class="form-control" name="tags">
                            <button type="submit" class="btn btn-primary">Submit</button>
                <div class="row mt-2 posts">
                    {% for post in posts %}
                    <div class="col-md-6">
                        <div class="cards">
                            <div class="row no-gutters border rounded flex-md-row mb-4 shadow-sm h-md-250">
                                <div class="col p-4 d-flex flex-column position-static">
                                    <h3 class="my-1"><a href="{% url 'detail' post.slug %}">{{post.title}}</a></h3>
                                    <div style="display:flex">
                                        {% for tag in post.tags.all %}
                                        <a href="{% url 'tagged' tag.slug %}" class="mr-1 badge badge-primary">#{{ tag }}</a>
                                        {% endfor %}
                                    <p class="mb-auto">{{post.description}}</p>
                                    <p class="mb-auto text-muted">{{post.published}}</p>
                    {% endfor %}
{% endblock content %}

Next, open the core/templates/detail.html file and the add:

{% extends 'base.html' %}

{% block content %}
<div class="container mt-5">
    <div class="row">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">
                <div class="card-body">
                    {% for tag in post.tags.all %}
                    <a href="#" class="badge badge-info" >{{ tag }}</a>
                    {% endfor %}
{% endblock content %}
Step 9: Creating URLs

In this section, we’ll create the urls to access our views.Go to the core/ file and update it as follows:

from django.urls import path
from . import views

urlpatterns = [
    path('tag-system/', views.home_view, name="home"),
    path('post/<slug:slug>/', views.detail_view, name="detail"),
    path('tag/<slug:slug>/', views.tagged, name="tagged"),

Next, we will require the modify the your root preoject folder lets update the file.

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('', include('core.urls')),
Run the Server

In this step, we’ll run the local development server for playing with our app without deploying it to the web.

python runserver

Next, go to the address with a web browser.


I Hope It will help you....