How to add dropdown navbar in Django

In this Python Django tutorial, I will explain how to add dropdown navbar in Django in simple steps.

Recently, I have been creating a website for PythonGuides using the Django framework. And I needed a navigation bar with a dropdown menu to add blog categories.

So, I have done some research and added a navbar with a dropdown in the website using Django which looks as follows.

how to add navbar template in python django
Add Dropdown navbar in Django

Here we will see:

  • What is the navigation bar?
  • How to create a navigation bar in Django using bootstrap4
  • How to add dropdown navbar in Django
  • Add dropdown navbar in Django to add blog categories
  • How to set up a Django project in simple steps
  • Creating a function-based view to render a template

At the end of this article, you can also download the code for adding a navbar with a dropdown menu on the website using Django.

Dropdown navbar menu on my Django

Now, let us first understand what is Navigation Bar and learn step by step to add a navbar template with a dropdown menu using Django.

Django Navigation Bar

Navigation Bar is a part of a graphical user interface that is designed to make it easier for users to locate links to all the pages that we want our visitors to read. 

Usually, a navigation bar with the most significant pages at the top-left and the least significant pages at the top-right of the navigation menu appears at the top of our website.

How to add dropdown navbar in Django to add blog categories

Now, we will see an example related to the creation of a navbar with a dropdown menu to add links of the different blog categories.

Set up Django Project

To start a Django project, open the terminal and enter the following command. Here, DropdownNavbarProject is the name of the Django Project.

django-admin startproject DropdownNavbarProject

It will make a folder called DropdownNavbarProject and to enter the project, type the below command in the terminal.

cd DropdownNavbarProject

Create a Django app named MyApp inside this project folder, by typing the below command in the terminal.

python manage.py startapp MyApp
add dropdown navbar in Django
Django Project and App

To activate this app, add the app name to the INSTALLED_APP list located in the settings.py file.

python django add navbar in python django
Install MyApp

By default, Django includes a urls.py file in the project directory to map the newly constructed app inside of it. To do so, add the below code in it.

from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('MyApp.urls')),
]

Read: Python Django vs Flask

Add dropdown navbar in Django using bootstrap

In Django, the front end of the application is defined in the Django template, so for this, create a subdirectory called Templates in the main project directory to store all of the project templates.

Then, to refer to the Templates folder’s location, update the DIRS by opening the settings.py file.

Dropdown menu in the navbar in Django
Adding Location of Template Folder

To define the template having a navigation bar with a dropdown menu create an HTML file named home.html inside the Templates folder. Add the below-given code in it.

<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css"
        integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

    <title>PythonGuides</title>
</head>

<body>
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
        <a class="navbar-brand" href="#">PythonGuides</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>

        <div class="collapse navbar-collapse" id="navbarSupportedContent">
            <ul class="navbar-nav mr-auto">
                <li class="nav-item active">
                    <a class="nav-link" href="\">Home <span class="sr-only">(current)</span></a>
                </li>
                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button"
                        data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                        Blogs
                    </a>
                    <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                        <a class="dropdown-item" href="https://pythonguides.com/django/">Django</a>
                        <a class="dropdown-item" href="https://pythonguides.com/matplotlib/">Matplotlib</a>
                        <a class="dropdown-item" href="https://pythonguides.com/turtle/">Turtle</a>
                        <a class="dropdown-item" href="https://pythonguides.com/tkinter/">Tkinter</a>
                    </div>
                </li>
            </ul>
        </div>
    </nav>
    <div class="container my-3">
        <h1 style="text-align:center;">Welcome to Python Guides</h1>
    </div>

    <div class="card">
        <div class="card-body">
            <h3 style="text-align:center;">Thanks for landing on this page to know more about PythonGuides.com.</h3>
            <br>
            <h6>I welcome you to the website and hopefully, you got to learn something in Python. I started this website
                to share my finding and learnings in Python with you.</h6>
            <h6>To keep things simple, I am trying to write a lot of articles on Python. Feel free to give your valuable
                comments and also share the articles if you are liking and hoping it will be helpful to someone.</h6>
            <br>
            <h2 style="text-align:center;">Also, Subscribe to Our YouTube Channel for FREE Python Video Tutorials.</h2>
        </div>
    </div>

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
        integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
        crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js"
        integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
        crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js"
        integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
        crossorigin="anonymous"></script>
</body>

</html>
  • To load our CSS, place Bootstrap and jQuery CDN in the head tag before any other stylesheets.
  • In the body tag, include the nav tag with the classes navbar and navbar-expand-lg.
  • Add a div tag with class collapse navbar-collapse and also add another div with class dropdown-menu to add a dropdown menu bar for adding blog categories.
  • Then, we add a div tag with a class card to add the content that we want to show on the Home page.

Django View

To define the main logic for rendering the navbar with a dropdown menu, we open the views.py file and add the below-given code.

from django.shortcuts import render

# Create your views here.

def home(request):
    return render(request,'home.html')

Here, we create a function-based view named home to render to the home.html template.

Now, we map the view with the URL in order to call it, thus we must create a file called urls.py in the app directory. Include the code below in it.

from django.urls import path
from MyApp import views

urlpatterns = [
    path("", views.home, name="home"),   
]

Read: Python Django vs ReactJS

Execute Contact Form Django Application

The manage.py file for Django includes a built-in subcommand called runserver that will begin a development server for the particular Django project.

Type the below-given command in the terminal and run the server.

python manage.py runserver

It successfully opens the Django navbar with a dropdown menu that looks like this.

how to add navbar template in python django
Django navbar with dropdown menu

Click on the Blogs dropdown and it will show blog categories. For example, Django, Matplotlib, Turtle, etc.

add navbar template for blog categories using django
Blogs Dropdown with different categories

Click on any of the blog categories, and it will move us to blog posts of the selected category.

For example, here I click on Django and it will move to the webpage having blog posts related to the Django web framework.

python django add navbar with dropdown menu
Blog Posts Page related to Django

This is how we can add a nav bar with a dropdown menu in Python Django.

Read: Python Django form validation

Download the complete code of the Django navbar with a dropdown menu

Conclusion

With this, we have successfully created a navbar with a dropdown menu in Django using bootstrap. Additionally, we have learned to create a function-based view that renders the template.

Additionally, we have covered the following topics.

  • What is the navigation bar?
  • How to create a navigation bar in Django using bootstrap4
  • How to add dropdown navbar in Django
  • Add dropdown navbar in Django to add blog categories
  • How to set up a Django project in simple steps
  • Creating a function-based view to render a template

You may also like to read the following Python Django tutorials.