DEV Community

Cover image for How To Make A Sub And Sub Sub Categories In Django [Most Important]
Shivam Rohilla
Shivam Rohilla

Posted on • Updated on

How To Make A Sub And Sub Sub Categories In Django [Most Important]

Hello Devs, in this category I'm gonna teach you how to make categories, sub categories and sub sub categories in django in simple steps.

Post Link:- https://pythondjangogeek.com/python/how-to-make-a-sub-and-sub-sub-categories-in-django/

Linkedin:- https://www.linkedin.com/in/shivamrohillaa/

Github Repo:- https://github.com/ShivamRohilllaa/django-
categories-tree

Enter fullscreen mode Exit fullscreen mode

Django Categories

Screenshot (91)

Django Sub Categories

Screenshot (91)

Django Sub sub categories

Screenshot (92)

Make a model for Django categories.

class Category(models.Model):
    parent = models.ForeignKey('self', related_name='children', on_delete=models.CASCADE, blank = 
    True, null=True)
    title = models.CharField(max_length=100) 
    slug = AutoSlugField(populate_from='title', unique=True, null=False, editable=False)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

    class Meta:
        #enforcing that there can not be two categories under a parent with same slug

        # __str__ method elaborated later in post.  use __unicode__ in place of

        unique_together = ('slug', 'parent',)    
        verbose_name_plural = "categories"     

    def __str__(self):                           
        full_path = [self.title]                  
        k = self.parent
        while k is not None:
            full_path.append(k.title)
            k = k.parent
        return ' -> '.join(full_path[::-1])  
Enter fullscreen mode Exit fullscreen mode

Write code in Views.py

def home(request):
    catg = Category.objects.filter(parent=None)
    context = {'catg':catg}    
    return render(request, 'index.html', context)
Enter fullscreen mode Exit fullscreen mode

Now render everything in your templates

Make an index.html file
And start fetching the details in the HTML file.

carbon (2)

Thank you

Shivam Rohilla | Python Developer

Top comments (3)

Collapse
 
gurnitha profile image
I Nyoman Gurnitha

hi,
thanks for this great tutorials.
i followed you way, but i end up without able to show the sub-sub category.
i will send you my code to your email.
pls have a look.

thanks.
i am nyoman, form bali, indonesia

Collapse
 
nabirhossain profile image
Nabir Hossain

I am new in Django. I follow your tutorial but I can not make url for subcategory. Please reply.

Collapse
 
shivamrohilla profile image
Shivam Rohilla

shivamrohillaa@gmail.com this is my email, please send your bugs or problems with the pics ok