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.
Similar Reads
initial â Django Form Field Validation
Built-in Form Field Validations in Django Forms are the default validations that come predefined to all fields. Every field comes in with some built-in validations from Django validators. Each Field class constructor takes some fixed arguments. initial is used to change the value of the field in the
4 min read
Exception Handing in Django
In this article, we will explore exception handling in Django, examining its significance and learning how to effectively manage exceptions. Through a practical example, we will illustrate the concept and subsequently delve into the solutions for handling exceptions. Exception Handing in DjangoHere,
6 min read
Django Static File
Static Files such as Images, CSS, or JS files are often loaded via a different app in production websites to avoid loading multiple stuff from the same server. This article revolves around, how you can set up the static app in Django and server Static Files from the same.Create and Activate the Virt
3 min read
label â Django Form Field Validation
Built-in Form Field Validations in Django Forms are the default validations that come predefined to all fields. Every field comes in with some built-in validations from Django validators. Each Field class constructor takes some fixed arguments. label is used to change the display name of the field.
4 min read
Views In Django | Python
Django Views are one of the vital participants of the MVT Structure of Django. As per Django Documentation, A view function is a Python function that takes a Web request and returns a Web response. This response can be the HTML contents of a Web page, a redirect, a 404 error, an XML document, an ima
6 min read
Django Installation and Setup
Installing and setting up Django is a straightforward process. Below are the step-by-step instructions to install Django and set up a new Django project on your system. Prerequisites: Before installing Django, make sure you have Python installed on your system. How to Install Django?To Install Djang
2 min read
if - Django Template Tags
A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to template, but also provides some
3 min read
Middleware in Django
Middleware is a series of processing layers present between the web server and the view (controller in some frameworks), allowing the user to intercept, modify, and add behavior to these requests and responses. What is Middleware in Django?In Python Django, middleware is a framework that provides a
9 min read
How to Install Django in Kaggle
Django is a powerful, high-level web framework used for rapid development of secure and maintainable websites. While Kaggle is typically used for data science and machine learning, we may want to explore Django's functionalities in a Kaggle notebook for testing purposes. In this tutorial, we'll walk
3 min read
now - Django Template Tags
A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to template, but also provides some
2 min read