Navigation refers to how users move through different sections of a web application. In Django, navigation is handled by combining URLs, views, and templates. By defining URL patterns, associating them with views, and linking them in templates, we can create a seamless experience for users as they move through our website.
In this article, we will explore how to set up and manage navigation in a Django project effectively. We will cover URL mapping, setting up navigation in templates, dynamic navigation, and best practices.
Understanding URL Mapping in Django
Django uses URLs to map different views to web addresses. Each URL in a Django project points to a specific view, which handles the request and renders the corresponding template.
The basic structure of URL mapping in Django looks like this:
urls.py
Python
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('about/', views.about, name='about'),
path('contact/', views.contact, name='contact'),
]
In this example, we define three URLs:
'/': maps to the home view.'/about/': maps to the about view.'/contact/': maps to the contact view.
Setting Up Navigation in Django
To implement navigation, we need to perform the following steps: define URLs, create views for those URLs, and add links in templates to facilitate navigation.
Let's start with setting up our Django Project:
python -m venv environment
environment\Scripts\activate
pip install django
django-admin stratproject navigation_tutorial
django-admin startapp navigation
Now add this app to the settings.py:
Python
# Add the app to INSTALLED_APPS
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'navigation',
]
Step 1 - Creating Views for Navigation
The first step is to create views. A view is a Python function that handles the logic for a given page.
navigation/views.py
Python
from django.shortcuts import render
def index(request):
return render(request, 'navigation/index.html')
def about(request):
return render(request, 'navigation/about.html')
def contact(request):
return render(request, 'navigation/contact.html')
Each view renders an HTML template that will be shown to the user. In this example, the index view will render the index.html template, and similarly for the other views.
Step 2 - Defining URLs
After creating view, the next step in setting up navigation in Django is defining URLs. URLs help route requests to the appropriate views. In Django, we define URLs in the urls.py file of our app.
Python
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('about/', views.about, name='about'),
path('contact/', views.contact, name='contact'),
]
Here, we have created URL patterns for three pages: home (index), about, and contact.
Step 3 - Creating Navigation Links in Templates
The final step is to create navigation links in our templates that allow users to move between different pages. We can do this using Django’s {% url %} template tag, which generates the appropriate URL based on the name of the view.
Before creating templates, let's modify templates settings in settings.py file:
Python
# Template settings
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
The above settings tells Django to find HTML files in the templates directory.
Let's create base HTML file.
In the templates directory, create a navigation/base.html:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Navitaion in Django Tutorial</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH"
crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-expand-lg bg-body-tertiary">
<div class="container-fluid">
<button class="navbar-toggler" type="button"
data-bs-toggle="collapse"
data-bs-target="#navbarNav"
aria-controls="navbarNav"
aria-expanded="false"
aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="{% url 'index' %}">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'about' %}">About Us</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'contact' %}">Contact Us</a>
</li>
</ul>
</div>
</div>
</nav>
<h1>Welcome to Navigation in Django</h1>
{% block content %}
{% endblock %}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz"
crossorigin="anonymous"></script>
</body>
</html>
In this template, we use the {% url 'index' %} tag to link to the home page, and similarly for the about and contact pages. This navigation bar will be included on every page that extends base.html.
Let's create other HTML Files we used in our views: index.html, contact.html, and about.html
HTML
<!-- index.html -->
{% extends 'navigation/base.html' %}
{% block content %}
<h2>This is index.html</h2>
{% endblock %}
HTML
<!-- about.html -->
{% extends 'navigation/base.html' %}
{% block content %}
<h2>This is about.html</h2>
{% endblock %}
HTML
<!-- contact.html -->
{% extends 'navigation/base.html' %}
{% block content %}
<h2>This is contact.html</h2>
{% endblock %}
Step 4 - Run the Django Server
python manage.py runserver
Visit the following URL to see the result.
- http://127.0.0.1:8000/
- http://127.0.0.1:8000/about/
- http://127.0.0.1:8000/contact/
Output:
Conclusion
Navigation is an essential part of any web application, and Django provides powerful tools to help us manage it efficiently. By defining URLs, creating views, and using Django’s template tags, we can create flexible and user-friendly navigation for our website. Whether it's static navigation, dynamic menus, or breadcrumbs, Django has us covered.
Incorporate best practices to keep our navigation simple, scalable, and easy to maintain, ensuring a better experience for both developers and users.
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice