How to create Dynamic menu from Database using Django Python

In this article, we will learn how to create a dynamic menu from Database using Django Python. Dynamic menus are very useful when you set access permission to users or restrict some pages to particular users at runtime.

A database-driven dynamic menu is very helpful.

This article creates a dynamic menu from the MYSQL database, Django, and Python.

Let’s start

This article uses Rest Framework “How to Create Dynamic menu from Database using Django Python”.

pip install djangorestframework

Create table in mysql

CREATE TABLE `dynamicmenu_mainmenu` (  `id` bigint(20) NOT NULL,  `menucode` int(11) NOT NULL,  `menuname` varchar(100) NOT NULL,  `menutype` int(11) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE `dynamicmenu_menulist` (  `id` bigint(20) NOT NULL,  `Menucode` int(11) NOT NULL,  `MenuType` int(11) NOT NULL,  `menuname` varchar(100) NOT NULL,  `submenuname` varchar(100) NOT NULL,  `menulink` varchar(100) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Insert the Data into a particular table using the below SQL insert statement

INSERT INTO `dynamicmenu_mainmenu` (`id`, `menucode`, `menuname`, `menutype`) VALUES(1, 1, 'Administrator', 1),(2, 2, 'Bank Account', 2),(3, 3, 'Deposit', 3),(4, 4, 'Withdraw', 4),(5, 5, 'Insurance', 5),(6, 6, 'Mutual Fund', 6),(7, 7, 'Employee', 7),(8, 8, 'Attendance', 8),(9, 9, 'Pigmy', 9),(10, 10, 'Pigmy Collection', 10);
INSERT INTO `dynamicmenu_menulist` (`id`, `Menucode`, `MenuType`, `menuname`, `submenuname`, `menulink`) VALUES(1, 1, 1, 'Administrator', 'Bank', ''),(2, 2, 1, 'Administrator', 'Branch', ''),(3, 3, 1, 'Administrator', 'Department', ''),(4, 4, 1, 'Administrator', 'Company', ''),(5, 5, 2, 'Bank Account', 'Bank Account', ''),(6, 3, 3, 'Deposit', 'Deposit', ''),(7, 4, 4, 'Withdraw', 'Withdraw', ''),(8, 5, 5, 'Insurance', 'Insurance', ''),(9, 6, 6, 'Mutual Fund', 'Mutual Fund', ''),(10, 7, 7, 'Employee', 'Employee', ''),(11, 8, 8, 'Attendance', 'Attendance', ''),(12, 9, 9, 'Pigmy', 'Pigmy', ''),(13, 10, 10, 'Pigmy Collection', 'Pigmy Collection', '');

# Database

MySQL database settings

 DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'djangodb',
        'USER': 'root',
        'PASSWORD': '',
        'HOST': 'localhost',
        'PORT': '3306',
    }
}

Now Create Model

models.py

from django.db import models

# Create your models here.

class mainmenu(models.Model):
    menucode = models.IntegerField()
    menuname = models.CharField(max_length=100)
    menutype = models.IntegerField()

    def __str__(self):
        return self.menuname

    mainmenulist_objects =models.Manager()

class MenuList(models.Model):
    Menucode= models.IntegerField()
    MenuType=models.IntegerField()
    menuname = models.CharField(max_length=100)
    submenuname = models.CharField(max_length=100)
    menulink = models.CharField(max_length=100)

    def __str__(self):
        return self.menuname
    
    menulist_objects = models.Manager()

Then create serializers.py

from  rest_framework  import serializers
from .models import  MenuList

class menuserializer(serializers.ModelSerializer):
    class Meta:
      model = MenuList
      fields =['menuname']

class submenuserializer(serializers.ModelSerializer):
    class Meta:
      model = MenuList
      fields =['menuname','submenuname','menulink','MenuType']

views.py

from django.shortcuts import render
from .models import MenuList,mainmenu
from .serializers import menuserializer,submenuserializer
from django.db.models import Avg, Count, Min, Sum
# Create your views here.

def dynamicmenu(request):

    try:       
          
        menuList = MenuList.menulist_objects.values('menuname').order_by('MenuType').annotate(Count('menuname'))
        submenuList = MenuList.menulist_objects.all().filter(id__in=[1,2,3,4,5,6,7,8,9,10])
        mainmenu = menuserializer(menuList,many=True)
        data = mainmenu.data
       # print(data)
        request.session['mainM'] = data

        submenudata = submenuserializer(submenuList,many=True)
        subdata = submenudata.data
        print(subdata)        
        request.session['submenu'] = subdata
        return render(request, 'index.html', {})  

    except Exception as identifier:         
        return render(request, 'index.html', {})  


index.html

 {% block content %} 

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">

        <title>Collapsible sidebar using Bootstrap 3</title>

        <!-- Bootstrap CSS CDN -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <!-- Our Custom CSS -->
      
        <!-- Scrollbar Custom CSS -->
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.min.css">

<style>
  
   /*
    DEMO STYLE
*/

@import "https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700";
body {
    font-family: 'Poppins', sans-serif;
    background: #fafafa;
}

p {
    font-family: 'Poppins', sans-serif;
    font-size: 1.1em;
    font-weight: 300;
    line-height: 1.7em;
    color: #999;
}

a,
a:hover,
a:focus {
    color: inherit;
    text-decoration: none;
    transition: all 0.3s;
}

.navbar {
    padding: 15px 10px;
    background: #fff;
    border: none;
    border-radius: 0;
    margin-bottom: 40px;
    box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.1);
}

.navbar-btn {
    box-shadow: none;
    outline: none !important;
    border: none;
}

.line {
    width: 100%;
    height: 1px;
    border-bottom: 1px dashed #ddd;
    margin: 40px 0;
}

/* ---------------------------------------------------
    SIDEBAR STYLE
----------------------------------------------------- */

.wrapper {
    display: flex;
    width: 100%;
    align-items: stretch;
}

#sidebar {
    min-width: 250px;
    max-width: 250px;
    background: #7386D5;
    color: #fff;
    transition: all 0.3s;
}

#sidebar.active {
    margin-left: -250px;
}

#sidebar .sidebar-header {
    padding: 20px;
    background: #6d7fcc;
}

#sidebar ul.components {
    padding: 20px 0;
    border-bottom: 1px solid #47748b;
}

#sidebar ul p {
    color: #fff;
    padding: 10px;
}

#sidebar ul li a {
    padding: 10px;
    font-size: 1.1em;
    display: block;
}

#sidebar ul li a:hover {
    color: #7386D5;
    background: #fff;
}

#sidebar ul li.active>a,
a[aria-expanded="true"] {
    color: #fff;
    background: #6d7fcc;
}

a[data-toggle="collapse"] {
    position: relative;
}

.dropdown-toggle::after {
    display: block;
    position: absolute;
    top: 50%;
    right: 20px;
    transform: translateY(-50%);
}

ul ul a {
    font-size: 0.9em !important;
    padding-left: 30px !important;
    background: #6d7fcc;
}

ul.CTAs {
    padding: 20px;
}

ul.CTAs a {
    text-align: center;
    font-size: 0.9em !important;
    display: block;
    border-radius: 5px;
    margin-bottom: 5px;
}

a.download {
    background: #fff;
    color: #7386D5;
}

a.article,
a.article:hover {
    background: #6d7fcc !important;
    color: #fff !important;
}

/* ---------------------------------------------------
    CONTENT STYLE
----------------------------------------------------- */

#content {
    width: 100%;
    padding: 20px;
    min-height: 100vh;
    transition: all 0.3s;
}

/* ---------------------------------------------------
    MEDIAQUERIES
----------------------------------------------------- */

@media (max-width: 768px) {
    #sidebar {
        margin-left: -250px;
    }
    #sidebar.active {
        margin-left: 0;
    }
    #sidebarCollapse span {
        display: none;
    }
}

</style>
    </head>
    <body>


        <div class="wrapper">
            <!-- Sidebar Holder -->
            <nav id="sidebar">
                <div class="sidebar-header">
                    <h3>Dynamic Menu</h3> 
                </div>

                <ul class="list-unstyled components">

                    {% for item in request.session.mainM %}
                  <li class="active">  
                 <a href="#{{ item.menuname }}" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle">{{ item.menuname }}</a>
                    <ul class="collapse list-unstyled" id="{{ item.menuname }}">
                     {% for  value in  request.session.submenu %}        
                        {% ifequal value.menuname item.menuname %}  
                          <li><a href="/{{ value.menulink }}">{{ value.submenuname }}</a></li>      
                         {% endifequal %} 
                      {% endfor %}  

                   </li>  
                  </ul>
                   {% endfor %} 
            </ul>
               
            </nav>

            <!-- Page Content Holder -->
            <div id="content">

                <nav class="navbar navbar-default">
                    <div class="container-fluid">

                        <div class="navbar-header">
                            <button type="button" id="sidebarCollapse" class="btn btn-info navbar-btn">
                                <i class="glyphicon glyphicon-align-left"></i>
                                <span>Toggle Sidebar</span>
                            </button>
                        </div>

                        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                            <ul class="nav navbar-nav navbar-right">
                                <li><a href="#">Page</a></li>
                            </ul>
                        </div>
                    </div>
                </nav>

            
            </div>
        </div>




        <!-- jQuery CDN -->
       <script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
        <!-- Bootstrap Js CDN -->
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
        <!-- jQuery Custom Scroller CDN -->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.concat.min.js"></script> 

        <script type="text/javascript">
            $(document).ready(function () {              
     
            $('#sidebarCollapse').on('click', function () {
                $('#sidebar').toggleClass('active');
            });
      
            
            });
        </script>
    </body>
</html>

 {% endblock %}



See More: How to Upload Files in Django Python

Now then Execute

4.7 3 votes
Article Rating
Subscribe
Notify of
guest

3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Asger Ali
Asger Ali
1 year ago

bro super video such a coding i have not seen in any video.
but I have comment you but no response. some of the navbar is not working eg
bank account, pigmy, pigmy connection. bro can you please add url link for 2 or 3 apps with crut o

Martin L.
Martin L.
10 months ago

Excellent tutorial. Got the code working quickly.
Two small notes:
1) ifequal is deprecated in recent django versions, just use if a == b.
2) djangorestframework must of course be added to the Django applications.