Django / Django Views and URL Routing

Configuring URL Routing with path()

This tutorial will guide you through configuring URL routing using the path() function in Django. It is a powerful and readable way to define URL patterns.

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Explains how to create views and configure URL routing in Django applications.

Configuring URL Routing with path() in Django

1. Introduction

1.1 Tutorial Goal

In this tutorial, we will learn about URL routing in Django using the path() function. We will understand how Django uses this function to map URLs to views, and how to configure it for our application.

1.2 Learning Outcomes

By the end of this tutorial, you will be able to configure URL routing for your Django application using the path() function.

1.3 Prerequisites

You should have Python and Django installed on your machine. Basic familiarity with Django views and URLs is also recommended.

2. Step-by-Step Guide

2.1 URL Routing in Django

In Django, when a user makes a request to a URL, Django uses URL routing to decide which view to call. This is done by comparing the requested URL against a list of URL patterns defined in the application. The URL patterns are defined using the path() function in your application's urls.py file.

2.2 The path() Function

The path() function is imported from django.urls and it takes two required arguments: the route and the view, and two optional arguments: kwargs, and name.

  • route: This is a string that contains a URL pattern. When processing a request, Django starts at the first pattern in the list and makes its way down the list until it finds a pattern that matches the requested URL.
  • view: This is a view function which Django calls when it finds a matching pattern.
  • kwargs: Arbitrary keyword arguments can be passed in a dictionary to the target view.
  • name: Naming your URL lets you refer to it unambiguously from elsewhere in Django.

2.3 Best Practices and Tips

  • Keep your URL patterns as simple as possible. They should be easy to understand and maintain.
  • Use the name parameter for your URLs. It allows you to change the URL in one place and not have to remember to change it in every place it is used.

3. Code Examples

3.1 Basic URL Routing

# Import the path function
from django.urls import path

# Import your view
from . import views

# Define your URL patterns
urlpatterns = [
    # When the user requests the root URL, call the home function in views
    path('', views.home, name='home'),
]

In the example above, '' is the route, views.home is the view, and 'home' is the name of the URL pattern.

3.2 URL Routing with Parameters

urlpatterns = [
    # When the user requests /user/<username>, call the profile function in views
    path('user/<str:username>', views.profile, name='profile'),
]

In the example above, <str:username> is a URL parameter. str means that we expect a string, and username is the variable name that will be passed to the view. In our view, we can access it like this:

def profile(request, username):
    # Now you can use the username variable
    print(username)

4. Summary

In this tutorial, we learned about URL routing in Django and how to use the path() function to define URL patterns. We also learned how to pass parameters from the URL to our views.

5. Practice Exercises

5.1 Exercise 1

Create a URL pattern for a page that displays a blog post by its ID. The ID is an integer.

5.2 Solution 1

path('post/<int:post_id>', views.post_detail, name='post_detail'),

In this solution, <int:post_id> is a URL parameter. int means that we expect an integer, and post_id is the variable name that will be passed to the view.

5.3 Exercise 2

Create a URL pattern for the route /products/<category>/<product_id>/, where category is a string and product_id is an integer.

5.4 Solution 2

path('products/<str:category>/<int:product_id>/', views.product_detail, name='product_detail'),

In this solution, we have two URL parameters: <str:category> and <int:product_id>. In our view, we can access them like this:

def product_detail(request, category, product_id):
    # Now you can use the category and product_id variables
    print(category, product_id)

Keep practicing and experimenting with various routes and views. Happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

JavaScript Minifier & Beautifier

Minify or beautify JavaScript code.

Use tool

Timestamp Converter

Convert timestamps to human-readable dates.

Use tool

Markdown to HTML Converter

Convert Markdown to clean HTML.

Use tool

Case Converter

Convert text to uppercase, lowercase, sentence case, or title case.

Use tool

Interest/EMI Calculator

Calculate interest and EMI for loans and investments.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help