In Django, path converters are used in URL patterns to capture specific types of data from the URL and pass them as arguments to your views. Path converters are specified within angle brackets < >
in your URL patterns. Here are some common path converters and how to use them:
str (String Converter): This converter matches any non-empty string, excluding the path separator ('/').
pythonfrom django.urls import path
urlpatterns = [
path('example/<str:slug>/', views.example_view),
]
int (Integer Converter): Matches zero or any positive integer.
pythonfrom django.urls import path
urlpatterns = [
path('example/<int:year>/', views.example_view),
]
slug (Slug Converter): Matches any slug string consisting of ASCII letters (a-z, A-Z), numbers (0-9), hyphens, or underscores.
pythonfrom django.urls import path
urlpatterns = [
path('example/<slug:post_slug>/', views.example_view),
]
uuid (UUID Converter): Matches a Universally Unique Identifier (UUID) in string format.
pythonfrom django.urls import path
urlpatterns = [
path('example/<uuid:uuid_value>/', views.example_view),
]
path (Path Converter): Matches any string, including the path separator ('/').
pythonfrom django.urls import path
urlpatterns = [
path('example/<path:path_value>/', views.example_view),
]
custom_path_converter (Custom Path Converter):
You can also create your own custom path converter by subclassing django.urls.converters.StringConverter
and overriding its methods.
pythonfrom django.urls import path, register_converter
class MyConverter:
regex = '[a-zA-Z]+'
register_converter(MyConverter, 'myconverter')
urlpatterns = [
path('example/<myconverter:value>/', views.example_view),
]
In your views, make sure to define the corresponding parameter to capture the value passed by the path converter:
python# views.py
from django.shortcuts import render
def example_view(request, slug):
# Your view logic here
return render(request, 'example_template.html', {'slug': slug})
Remember to adapt the examples based on your project's requirements. The choice of path converters depends on the type of data you expect to capture from the URL.