How to add tags in Django

Use Django taggit 😋

Aymane Talibi
3 min readSep 16, 2020

[django-taggit] a simpler approach to tagging with Django. Add [“taggit”] to your [INSTALLED_APPS] then just add a TaggableManager to your model and go 👲

First thing you have to do is to copy this pip installer and run It in your cmd : pip install django-taggit

Now go to your settings.py and add ‘taggit’ to your [INSTALLED_APPS]:

You know now we have to add tags tou the object we want to make them for, so open your ‘model.py’ and import [TaggableManager] from [taggit.managers] :

from taggit.managers import TaggableManager

Now you have to add [a_variable=TaggableManager] to the object you want to add tags for It.
in my case I name the variable ‘Tags’ :

Now return to your cmd and make migrations, then migrate :

Then go to your urls.py of the application you work on (! Not the file of the project), and add the following path :

path('tag/<slug:tag_slug>', views.the_name_of_the_function_in_views, name='name_It'),

And in the views.py import Tag :

from taggit.models import Tag

Then, add ‘tag_slug=None’ to the parrameters of the function you want to use It in. Now create a variable nammed ‘tag’ and give It None as value, then add a condition if the tag_slug is exist then the variable ‘tag’ and the object variable will being changed :

tag=None

if tag_slug :

tag=get_object_or_404(Tag,slug=tag_slug)

var_of_the_object=var_of_the_object.filter(tags__in=[tag])

and add the variable ‘tag’ to your HTML render function, example :

Now go to your HTML file, but beffore let’s take this example :

As you see tis is the element where I want to show tags

Now, in the HTML file in the container of showing the object you can use the ‘tag’ variable to show/add tags to your object.

In may case I use TaggableManager like this :

Now with runing the server and check my object, It look that the Tag element is added, but It don’t show any tags in the <dev> of tags :

So, I have to add some tags to my object in my django-admin, now with consulting the object in django-admin We should found a textbox with a label ‘tag’ :

But, if we read the text bellow textbox, we understand that the tags should been separated with a comma.
Now after adding some tags to the object It look like :

with all the tags added.

It was easy isn’t ? :) 👊

--

--