0
0
Djangoframework~5 mins

URL parameter type converters in Django

Choose your learning style9 modes available
Introduction

URL parameter type converters help Django understand what kind of data to expect in a URL. This makes your web app handle URLs more safely and clearly.

When you want to get a number from the URL and use it in your view.
When you want to accept only certain types of text in a URL, like a slug or a UUID.
When you want to make sure the URL parameter matches a pattern before your view runs.
When you want to convert URL parts directly to Python types like int or UUID.
When you want to avoid errors by validating URL inputs automatically.
Syntax
Django
path('route/<converter:name>/', view_function, name='route_name')

The converter tells Django what type to expect (like int, str, slug, uuid, or path).

The name is the variable name your view will receive.

Examples
This expects an integer called id from the URL and passes it to the view.
Django
path('article/<int:id>/', views.article_detail, name='article_detail')
This expects a slug (letters, numbers, hyphens, underscores) called username.
Django
path('user/<slug:username>/', views.user_profile, name='user_profile')
This accepts a full path including slashes as file_path.
Django
path('files/<path:file_path>/', views.show_file, name='show_file')
This expects a UUID string as order_id.
Django
path('order/<uuid:order_id>/', views.order_detail, name='order_detail')
Sample Program

This Django URL pattern uses an int converter to get an article ID from the URL. The view shows the ID in the response.

Django
from django.urls import path
from django.http import HttpResponse

def show_article(request, id):
    return HttpResponse(f"Article ID is {id}")

urlpatterns = [
    path('article/<int:id>/', show_article, name='show_article'),
]
OutputSuccess
Important Notes

If the URL part does not match the converter type, Django returns a 404 error automatically.

You can create custom converters if needed by defining a class with regex, to_python(), and to_url() methods.

The str converter matches any text except slashes, so it is the default if no converter is given.

Summary

URL parameter type converters tell Django what kind of data to expect in URLs.

They help validate and convert URL parts automatically before your view runs.

Common converters include int, str, slug, uuid, and path.