Django / Django Views and URL Routing

Working with Dynamic URL Parameters

This tutorial introduces working with dynamic URL parameters in Django. You will learn how to capture values from URLs and pass them to views.

Tutorial 5 of 5 5 resources in this section

Section overview

5 resources

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

1. Introduction

In this tutorial, we will explore how to work with dynamic URL parameters in Django. URLs in Django are designed to be flexible, allowing for a wide range of different URL patterns. An important part of this flexibility is the ability to capture values directly from the URL itself, which are called dynamic URL parameters.

You will learn how to:
- Define dynamic URL parameters in your URL configurations
- Capture these parameters in your views
- Use captured parameters to manipulate your views

Prerequisites:
- Basic understanding of Python
- Familiarity with Django's fundamental concepts such as views and URLs

2. Step-by-Step Guide

2.1 URL Parameters

In Django, URL parameters are specified in your URLconf (typically found in the urls.py file). A URL parameter is defined by enclosing a variable name in angle brackets (< >). For example, in the URL pattern path('blog/<int:year>/', views.blog_archive), year is a URL parameter.

2.2 Capturing URL Parameters

To capture these URL parameters, your view function should include a parameter with the same name. In the blog_archive view, we might define it as follows:

def blog_archive(request, year):
    # ...

Here, year is a captured URL parameter. Django will automatically pass the value from the URL to your view.

2.3 Using URL Parameters

You can use these parameters to filter database queries, customize content, or any number of other tasks.

3. Code Examples

3.1 Defining URL Parameters

In your urls.py file, define a URL with a parameter:

from django.urls import path
from . import views

urlpatterns = [
    path('blog/<int:year>/', views.blog_archive),
]

Here, <int:year> is a URL parameter of type integer. year is the variable name which will be passed to the view.

3.2 Capturing and Using URL Parameters

In your views.py file:

from django.shortcuts import render
from .models import Blog

def blog_archive(request, year):
    # Get all blog posts from the given year
    blog_posts = Blog.objects.filter(pub_date__year=year)

    return render(request, 'blog/archive.html', {'blog_posts': blog_posts})

Here, the year parameter is used to filter the Blog objects by publication date. The filtered blog_posts are then passed to the archive.html template.

4. Summary

In this tutorial, we've covered how to define, capture, and use dynamic URL parameters in Django. These parameters provide a powerful way to customize your views and make your URLs more dynamic and flexible.

Next steps for learning might include exploring more advanced URL configurations, such as optional parameters and complex query strings.

Additional resources:
- Django's official documentation on URL dispatcher
- Django for Beginners by William S. Vincent

5. Practice Exercises

  1. Exercise: Define a URL pattern that includes two parameters: a string representing a category, and an integer representing a product id. Capture these parameters in a view and use them to display a specific product from a specific category.

Solution: In urls.py:

python path('products/<str:category>/<int:id>/', views.product_detail)

In views.py:

python def product_detail(request, category, id): product = Product.objects.get(category=category, id=id) return render(request, 'product_detail.html', {'product': product})

  1. Exercise: Define a URL pattern for a blog post that includes a parameter for the post's slug (a string). Capture this parameter in a view and use it to display the corresponding blog post.

Solution: In urls.py:

python path('blog/<str:slug>/', views.blog_post)

In views.py:

python def blog_post(request, slug): post = BlogPost.objects.get(slug=slug) return render(request, 'blog_post.html', {'post': post})

Remember to continue practicing and experimenting with different types of URL parameters and ways to use them in your 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

PDF Password Protector

Add or remove passwords from PDF files.

Use tool

Unit Converter

Convert between different measurement units.

Use tool

PDF Compressor

Reduce the size of PDF files without losing quality.

Use tool

Keyword Density Checker

Analyze keyword density for SEO optimization.

Use tool

Open Graph Preview Tool

Preview and test Open Graph meta tags for social media.

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