Without dynamic routing, navigating web pages would be difficult. You would have to type the full path of every page you visit on the browser. What a terrible user experience.

Dynamic Uniform Resource Locators (URLs), allow you to navigate to different pages on an app with the click of a button. Django makes it easy to design dynamic URLs. It has a URL Configuration module (URLconf) that connects URL expressions to views.

All code in the URLconf is in Python syntax, making it easy to create dynamic URLs. Let's learn more about dynamic URLs by building a Django project.

1. Create a Django Project

First, create a Django project and application (app).

Name your app Boma-watch. The app will collect location, description, and resident numbers from various neighborhoods. Create a model named NeighborHood. Use the model to add information about the neighborhoods into a database. Learn how to create models in Django and the database if you are unfamiliar.

Next, create a view function for the neighborhoods.

2. Create a View Function

In Django, views are Python functions that take HTTP requests and return responses. On a web page powered by Django, views perform varied tasks and missions.

To execute a view, you must call it via a URL. A URL is a unique path to a resource on the web. The resource can be an HTML page, image, or an API endpoint.

Create a URL that retrieves neighborhood data based on the parameters passed. To do so, you can use the primary key (pk) or Identification (id) to retrieve the information. You will use one template to do this.

You can create views by defining them in a file called views.py in the app's folder. Start by importing the render function from Django to display data at the URL. Also import the NeighborHood model from models.py.

        from django.shortcuts import render
from .models import NeighbourHood

Next, create a view function named home that displays all neighborhoods on the home template. The NeighborHood.objects.all() function receives data for all the neighborhoods from the database.

        def home(request):
     neighborhoods = NeighbourHood.objects.all()
     return render (request, "home.html", {'neighborhoods':neighborhoods})

Also, create a view function for join_hood that will display a neighborhood's information. The NeighbourHood.objects.get(id=id) function requests data according to the ID. The information is then rendered on a template.

        def join_hood(request, id):
     neighborhood = NeighbourHood.objects.get(id=id)
     return render (request, 'join_hood.html', {'neighborhood':neighborhood})

Later on, when you navigate to a neighborhood, you will be able to see its profile information.

3. Create a Dynamic URL

You can now create a dynamic URL for the view function you created.

        from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
 
urlpatterns = [
      path ('home', views.home, name='home'),
      path ('join_hood/<str:id>/', views.join_hood, name='join_hood'),
]
 
if settings.DEBUG:
     urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)

Import path from Django URLs to create paths for the view. Then import the view functions from views.py.

The join_hood URL has a placeholder in angle brackets: <str:id>. This captures that part of the URL and sends it to the view.

The angle brackets usually include a converter specification. The specification may either be a string (str) or integer (int). Django also offers slug, path, or universally unique identifiers (uuid). The specification limits the type of variable or number of characters passed in the URL to the view.

Giving the URLs a name will help identify them on the templates.

The static and staticfiles imports display static files on the URL paths. Learn more about how to structure URL parameters in the official Django documentation.

4. Add URL to a Template

Once you have added the view function to the URL, create an HTML template to display the data. You name the template join_hood.html.

        {% extends "base.html" %}
 
{% load static %}
 
{% block content %}
<div class="card mb-3" style="max-width:fit content;">
    <div class="row g-0">
        <div class="col-md-4">
            <div class="col-md-8" >
                <div class="card-body">
                    <h5 class="card-title"> Welcome!</h5>
                    <p class="card-text pt-4"> Name: {{neighbourhood.name}}</p>
                    <p class="card-text pt-4"> Location: {{neighbourhood.location}}</p>
                    <p class="card-text pt-4"> Description: {{neighbourhood.description}}</p>
                    <p class="card-text pt-4"> Health Tel:{{neighbourhood.health_tell}}</p>
                    <p class="card-text pt-4"> Police Number: {{neighbourhood.police_number}}</p>
                    <p class="card-text pt-4"> Residents : {{neighbourhood.Count}}</p>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

Create the join_hood template in the app folder to display the neighborhood data. First, extend the base.html template with style sheets (bootstrap) that you will use to style the template. Then, render the variables that will display the information on the page.

Next, create a home.html template where you will display all neighborhoods.

        {% extends 'base.html' %}
 
{% load static %}
 
{% block content %}
<div class="container" style="color:black;">
    <img src="{{neighborhood.hood_logo.url}}" class="card-img-top" alt="{{user.neighborhood.name}}">
 
    <div class="row">
        {% for neighborhood in neighborhoods %}
        <div class="col-md-4">
            <div class="card mb-4" style="min-height:340px">
                <img src="{{neighborhood.hood_logo.url}}" class="card-img-top" alt="{{user.hood.name}}">
 
                <div class="card-body">
                    <h5 class="card-title">
                       {{neighborhood.name}}
                       ({{neighborhood.location}})
                       <span class="ml-4">{{neighborhood.Count}} member{{neighborhood.members.count|pluralize}}</span>
                   </h5>
 
                    <p class="card-text">{{neighborhood.description}}</p>
                    <p class="card-text">{{neighborhood.member.Count}}</p>
 
                    <a href="{% url 'join_hood' neighborhood.id %}" class="btn btn-primary btn-sm">Join Hood</a>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

On the home page, render all the information you want to display about the neighborhoods. You will add a button and an anchor tag on the home page. The anchor tag has the URL name and neighborhood ID.

When clicked, the button navigates to the neighborhood of that ID. The home template appears at the URL http://127.0.0.1:8000/home/. The picture below demonstrates this page:

Home page displays all the neighborhoods

5. Test Dynamic Routing

Now, you can test if the dynamic routing works on the template. When you click the join hood button, It navigates to the join_hood template. The join_hood template displays profile information about the neighborhood you selected.

You will also see the ID of the neighborhood displayed on the browser URL http://127.0.0.1:8000/join_hood/2/

It will appear as shown below:

join_hood page displays details of neighborhood on browser

Congratulations! You have created a dynamic URL.

Why Use Django URLs?

Dynamic URLs are an important feature in web applications. Django makes it easy to design URLs according to your needs. It removes the limitations you might associate with other frameworks.

The URLconf module is full of resources supporting Django URL creation. It also makes it easier to serve static files on templates and improves error handling.

Django has other features designed to optimize backend applications. It automates user authentication, content administration, and site maps, among other features.