<meta name="clckd" content="6301244fb7ed470eb1cd6b8c31d01ac4" />

How To Make A Sub And Sub Sub Categories In Django

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. 

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

Django Categories



Django Sub Categories


Django Sub sub categories


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:
            k = k.parent
        return ' -> '.join(full_path[::-1])  

Write code in Views.py

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

Now render everything in your templates

Make an index.html file

and start fetching the details in the HTML file.



Thank you

Shivam Rohilla | Python Developer

  • No Reviews Yet

Leave a Reply
Please Sign In For Comment.
Login or Signup
Shivam Rohilla
Hi, I'm Shivam Rohilla

Hi! My name is Shivam Rohilla. I am a Full Stack Web Developer, and I'm very passionate and dedicated to my work. With 2 years experience as a professional Full Stack Web Developer.

Follow Me:-

My social media links