Django models: you need to display the menu and submenus

Can you please help. That's the question. I have a menu, the name of the menu is 'catr' and there is a submenu 'subcat' , I want to make the entire menu list output, and if the menu id matches the menu, then a subcategory is output, but I don't understand how to implement it.Help please.Sorry if I didn't explain it clearly, I hope you will understand, thank you in advance

Here's what I tried to do enter image description here enter image description here

From what I can understand you can do this using functions in your models like this...

class Category(models.Model):
    name = models.CharField(max_length=100 db_index=True)
    slug= models.SlugField(max_length=255, unique=True, db_index=True, verbose_name = 'URL')
    
    def ___str__(self):
        return self.name
    
    def get_absolute_url(self):
        return reverse('category' kwargs={'cat_slug':self.slug})

    def get_sub_category(self):
        return Subcategory.objects.filter(parent_category=self)
    
    class Meta:
        verbose_name = 'Kатегоpии'
        verbose_name_plural = 'Kaтегоpии'
        ordering = ['id']

and in your templates do this...

{% for item in catr %}
    <li>
        {{item.name}}
        {% if item.get_sub_category %}
            <ul>
                {% for child in item.get_sub_category %} 
                    <li>{{ child.sub }}</li>
                {% endfor %}
            </ul>
        {% endif %}
    </li>
{% endfor %}
Back to Top