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 manage.py 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 setting.py

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

settings.py
....
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'core',
    'taggit'
]

Step 5: Create a Model

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

core/models.py
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
            tag_dict.save()

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 manage.py makemigrations
python manage.py 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.

core/forms.py
from django import forms
from .models import Post

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = [
            'title',
            'description',
            'tags',
        ]
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/views.py file and add.

core/views.py
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 = form.save(commit=False)
        newpost.slug = slugify(newpost.title)
        newpost.save()
        # Without this next line the tags won't be saved.
        form.save_m2m()
    context = {
        'posts':posts,
        'form':form,
    }
    return render(request, 'home.html', context)

def detail_view(request, slug):
    post = get_object_or_404(Post, slug=slug)
    context = {
        'post':post,
    }
    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:

core/templates/base.html
<html>
    <head>
        <title>Tuts-Station.com</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-tagsinput/0.8.0/bootstrap-tagsinput.css" />
        <style>
        .bootstrap-tagsinput .tag{
            margin-right: 2px;
            color: #ffffff;
            background: #2196f3;
            padding: 3px 7px;
            border-radius: 3px;
        }
        .bootstrap-tagsinput {
            width: 100%;
        }
    </style>
    </head>

    <body>
    {% block content %}{% endblock content %}
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-tagsinput/0.8.0/bootstrap-tagsinput.js"></script>
    <script>
    $("#post-form").submit(function(e){
        e.preventDefault();
        });</script>
    </body>
</html>

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

core/templates/home.html
{% 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">Tuts-Station.com</span></h3>
                    </div>
                    <div class="card-body">
                        <form method="POST">
                            {% csrf_token %}
                            <div class="mb-3">
                                <label>Title</label>
                                <input type="text" class="form-control" name="title" placeholder="Add title">
                            </div>
                            <div class="mb-3">
                                <label>Description</label>
                                <textarea type="text" class="form-control" name="description" placeholder="Add description"></textarea>
                            </div>
                            <div class="mb-3">
                                <label>Tags</label>
                                <input type="text" data-role="tagsinput" class="form-control" name="tags">
                            </div>
                            <button type="submit" class="btn btn-primary">Submit</button>
                        </form>
                    </div>
                </div>
                <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 %}
                                    </div>
                                    <p class="mb-auto">{{post.description}}</p>
                                    <p class="mb-auto text-muted">{{post.published}}</p>
                                </div>
                            </div>
                        </div>       
                    </div>
                    {% endfor %}
                </div>
            </div>
        </div>
    </div>    
{% endblock content %}

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

core/templates/detail.html
{% 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">
                    <h3>{{post.title}}</h3>
                    <small>{{post.published}}</small>
                </div>
                <div class="card-body">
                    {% for tag in post.tags.all %}
                    <a href="#" class="badge badge-info" >{{ tag }}</a>
                    {% endfor %}
                    <p>{{post.description}}</p>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock content %}
Step 9: Creating URLs

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

core/urls.py
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 urls.py your root preoject folder lets update the file.

example/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    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 manage.py runserver

Next, go to the address with a web browser.

http://localhost:8000/tag-system/

I Hope It will help you....