Wednesday, December 25, 2024
Google search engine
HomeLanguagesAdding Tags Using Django-Taggit in Django Project

Adding Tags Using Django-Taggit in Django Project

Django-Taggit is a Django application which is used to add tags to blogs, articles etc. It makes very easy for us to make adding the tags functionality to our django project.
Setting up Django Project
 

  • Installing django-taggit 
     
pip install django-taggit
  • ADD it to Main Project’s settings.py file 
     

Python3




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


  • Changes To models.py file 
     

Add TaggableManager in your post, blog, article modal

Python3




from django.db import models
from django.utils.timezone import now
from taggit.managers import TaggableManager
 
class Post(models.Model):
    postid = models.AutoField(primary_key=True)
    title = models.CharField(max_length=255)
    content = models.TextField()
    author = models.CharField(max_length=100)
    postauthor = models.ForeignKey(User, on_delete=models.CASCADE)
    slug = models.SlugField(unique=True)
    category = models.CharField(max_length=200)
    timestamp = models.DateTimeField(default=now, blank=True)
    tags = TaggableManager()


After adding TaggableManager run following commands in terminal

  • python manage.py makemigrations
    python manage.py migrate

The TaggableManager will show up automatically as a field in post modal 
 

 

The Taggit Modal will also appear automatically as a separate modal in admin panel 

 

Taggit Modal In Admin Panel

 

 

Adding tags 

1) If the tags input doesn’t contain any commas or double quotes, it will be taken as space-delimited list of 
tag names. 
 

Lazyroar for Lazyroar => "Lazyroar", "for", "Lazyroar"

2) If the tags input does contain commas or double quotes then : 
 

       
a) Lazyroar, Lazyroar for Lazyroar            =>   "Lazyroar", "Lazyroar for Lazyroar" 
b) "Lazyroar, forLazyroar" geek Lazyroarfor   =>   "Lazyroar, forLazyroar", "geek", "Lazyroarfor"
c) "Lazyroar, forLazyroar", geek Lazyroarfor  =>   "Lazyroar, forLazyroar", "Lazyroar Lazyroarfor"
d) Lazyroar "for" Lazyroar                 =>   "Lazyroar", "for", "Lazyroar"

 

After Adding Tags to the posts the taggit modal will look like :

 

All the tags which are associated with different posts will appear in tags modal under taggit

 

On clicking the particular tag, There will come a list of all the posts associated with that particular tag. Now this model can be used with the project like other models

 

RELATED ARTICLES

Most Popular

Recent Comments