How to add Tags to Your Django Models?

0
11148
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 settings.py and include taggit in your INSTALLED_APPS

INSTALLED_APPS = [
    ...
    'taggit'
]

Create Model

Now, open models.py 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):
    name=models.CharField(max_length=225)
    slug=models.SlugField(max_length=225, unique=True)
    subcategory=models.ForeignKey('SubCategory', related_name='prosubcat', on_delete=models.CASCADE, blank=True, null=True)
    totalprice=models.IntegerField()
    saleprice = models.IntegerField()
    title=models.CharField(max_length=225)
    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):
        return self.name

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

Create Form

In your forms.py:

from django import forms
from .models import Product

class ProductForm(forms.ModelForm):
    class Meta:
        model=Product
        fields=['name','slug','subcategory','totalprice','saleprice','title','description','overview','featured','tags']

Create Views

Let’s see views.py:

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):
   subcat=SubCategory.objects.all()
   common_tags = Product.tags.most_common()[:4]
   form = ProductForm(request.POST)
 if form.is_valid():
   newpost = form.save(commit=False)
   newpost.slug = slugify(newpost.name)
   newpost.save()
   form.save_m2m()
 context={
 '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 = {
        'post':post,
    }
    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 = {
        'tag':tag,
        'posts':posts,
    }
    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 %}
            </p>
Database Table of Django-taggit package
Tag name with slug
Output of Django-taggit