Back to Python
2026-03-215 min read

Vertical Menu (Python Programming)

Learn Vertical Menu (Python Programming) step by step with clear examples and exercises.

Title: Vertical Menu (Python Programming)

Why This Matters

In web development, a vertical menu is an essential element for organizing content and improving user experience. It allows users to navigate through different pages or sections of a website easily. In this lesson, we will learn how to create a functional vertical menu using Python programming with the Flask web framework. This skill can be beneficial for creating dynamic websites and improving your problem-solving abilities in web development.

Prerequisites

Before diving into the core concept, you should have a basic understanding of the following:

  1. Python syntax and data structures (variables, lists, functions)
  2. HTML and CSS basics
  3. Familiarity with web development concepts like HTTP requests, APIs, and templates
  4. Understanding of Flask web framework (optional but recommended for this lesson)

Core Concept

To create a vertical menu using Python and Flask, we will use the following steps:

  1. Install Flask:
pip install flask
  1. Create a new file called app.py and write the following code:
from flask import Flask, render_template

app = Flask(__name__)

nav_menu = [
{'text': 'Home', 'url': '/'},
{'text': 'About Us', 'url': '/about'},
{'text': 'Contact Us', 'url': '/contact'}
]

@app.route('/')
def home():
return render_template('index.html', nav=nav_menu)

if __name__ == "__main__":
app.run(debug=True)

In this code, we import the Flask module and create a new Flask web application. We define an array nav_menu containing menu items with their respective URLs. The @app.route('/') decorator defines a route for the home page that renders the index.html template with the navigation menu as an argument.

  1. Create a new folder called templates, and inside it, create another file called index.html. Write the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vertical Menu</title>
<style>
ul {
list-style-type: none;
padding: 0;
margin: 0;
}
li a {
display: block;
color: #333;
text-decoration: none;
padding: 15px;
}
li a:hover {
background-color: #f5f5f5;
}
</style>
</head>
<body>
<ul id="nav">
{% for item in nav %}
<li><a href="{{ item.url }}">{{ item.text }}</a></li>
{% endfor %}
</ul>
</body>
</html>

In this code, we define the CSS styling for our vertical menu and use a Jinja2 template to loop through the nav_menu array and generate HTML list items with links.

  1. Run your Flask application:
python app.py

Open your web browser and navigate to http://127.0.0.1:5000/. You should see a simple vertical menu that allows you to navigate between Home, About Us, and Contact Us pages.

Worked Example

Let's extend our example by adding a search functionality to the navigation bar. First, update app.py as follows:

from flask import Flask, render_template, request, redirect, url_for

... (previous code remains unchanged)

@app.route('/search', methods=['GET'])

def search():

query = request.args.get('q')

if not query:

return redirect(url_for('home'))

results = []

Add your search logic here (e.g., database queries, API calls)

return render_template('search.html', nav=nav_menu, results=results)

@app.route('/')

def home():

return render_template('index.html', nav=nav_menu)

... (previous code remains unchanged)


Now create a new file called `search.html` in the `templates` folder:

Search Results


Add the search form to `search.html`, and implement your search logic in the new `search()` function in `app.py`.

Common Mistakes

  1. Forgetting to import Flask: Make sure you have from flask import Flask, render_template, request, redirect, url_for.
  2. Incorrect template syntax: Ensure that your Jinja2 templates follow the correct syntax, using double curly braces for variables and loops (e.g., {{ item.url }}, {% for item in nav %}).
  3. Not defining routes: Make sure to define routes for each page or functionality you want to implement.
  4. Forgetting to run the Flask application: Don't forget to execute python app.py to start your web server.
  5. Incorrect HTML structure: Ensure that your HTML is well-structured and valid, with a proper DOCTYPE declaration, head, body, and closing tags.
  6. Not handling search results: If you are implementing a search functionality, make sure to handle the case where no results are found and display an appropriate message to the user.
  7. Security vulnerabilities: Be aware of potential security risks when working with user input, such as SQL injection attacks or cross-site scripting (XSS). Always sanitize and validate user input before using it in your application.

Practice Questions

  1. Add a new menu item for a "Login" page. How would you modify the nav_menu array and the home() function in app.py to achieve this?
  2. Implement a search functionality that searches through a list of predefined items (e.g., blog posts or products). How would you update the search() function in app.py and the search.html template to accomplish this?
  3. Add a dropdown menu to your vertical navigation bar. How would you modify the CSS, HTML, and Python code to create a dropdown menu structure?
  4. Implement user authentication for the "Login" page. What changes would you make to the existing code to require users to log in before accessing certain pages or functionality?
  5. Create a pagination system for displaying search results over multiple pages. How would you modify the search() function and the HTML templates to implement this feature?

FAQ

What is Flask, and why is it useful for creating web applications with Python?

  • Flask is a lightweight micro-framework that makes it easy to build web applications quickly using Python. It provides essential tools like routing, templates, and utilities for handling HTTP requests and responses.

How can I customize the appearance of my vertical menu using CSS?

  • You can modify the CSS styles in the `` section of your HTML template to change the colors, fonts, padding, and other properties of your vertical menu.

Can I use a database or an API to store and retrieve data for my search functionality?

  • Yes, you can use databases like SQLite or APIs to store and retrieve data for your search functionality. You'll need to implement the necessary logic in the search() function in app.py.

How do I deploy my Flask application to a web server so it's accessible to others?

  • There are several ways to deploy a Flask application, including using services like Heroku or AWS Elastic Beanstalk. You can also set up your own web server using tools like Gunicorn or uWSGI. Consult the Flask documentation for more information on deployment options.

How do I handle user authentication and authorization in my Flask application?

  • To handle user authentication, you can use various methods such as sessions, OAuth, or OpenID Connect. For authorization, you can implement role-based access control (RBAC) to restrict access to certain pages or functionality based on the user's role. Consult the Flask documentation for more information on these topics.
Vertical Menu (Python Programming) | Python | XQA Learn