I am trying to add a dropdown to my navbar in base.html
that shows multiple categories from a store. Each of these categories has a sub-category associated with it. I’ve created a model in Django that maps this relationship like so.
models.py
class CategoryView(models.Model):
parent = models.ForeignKey('self', related_name='children', on_delete=models.CASCADE, blank = True, null=True)
title = models.CharField(max_length=100)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
And I’m passing this model to the template using context processors as so
def categoriesdropdown(request):
catg = CategoryView.objects.filter(parent=None)
context = {'catg':catg}
return context
Now I am trying to display these categories and sub-categories as a multilevel dropdown using bootstrap. I have tried implementing mostly all solutions from the answers here:
Bootstrap 4: Multilevel Dropdown Inside Navigation
Bootstrap dropdown sub menu missing
https://mdbootstrap.com/docs/standard/extended/dropdown-multilevel/
But nothing seems to work.
Below is the dropdown from my template.
base.html
<div class="nav-item dropdown">
<a href="#" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" class="nav-link dropdown-toggle">Categories</a>
<ul class="dropdown-menu dropdown-menu2" aria-labelledby="dropdownMenuLink">
{% for category in catg %}
<li class="dropdown-submenu">
<a class="dropdown-item dropdown-toggle" href="#" id="multilevelDropdownMenu1" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">{{ category.title }}</a>
<ul class="dropdown-menu2" aria-labelledby="multilevelDropdownMenu1">
{% for subcategory in category.children.all %}
<li><a href="#" class="dropdown-item">{{ subcategory.title }}</a></li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
I can see that all the categories and sub-categories are listed properly in the dropdown, however my sub-categories appear right below the categories and not as a next level dropdown.
Note: The dropdown toggle appears as is and doesn’t work.
base.css
.dropdown-submenu {
position: relative;
}
.dropdown-submenu .dropdown-menu2 {
top: 10%;
left: 100%;
margin-top: -1px;
}
.navbar-nav li:hover > ul.dropdown-menu2 {
display: block;
}
How do I get the category toggles to work and only display the sub-categories when the toggle is clicked or hovered over?