How to use path converters in Django URL patterns



Image not found!!

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:

  1. str (String Converter): This converter matches any non-empty string, excluding the path separator ('/').

    python
    from django.urls import path urlpatterns = [ path('example/<str:slug>/', views.example_view), ]
  2. int (Integer Converter): Matches zero or any positive integer.

    python
    from django.urls import path urlpatterns = [ path('example/<int:year>/', views.example_view), ]
  3. slug (Slug Converter): Matches any slug string consisting of ASCII letters (a-z, A-Z), numbers (0-9), hyphens, or underscores.

    python
    from django.urls import path urlpatterns = [ path('example/<slug:post_slug>/', views.example_view), ]
  4. uuid (UUID Converter): Matches a Universally Unique Identifier (UUID) in string format.

    python
    from django.urls import path urlpatterns = [ path('example/<uuid:uuid_value>/', views.example_view), ]
  5. path (Path Converter): Matches any string, including the path separator ('/').

    python
    from django.urls import path urlpatterns = [ path('example/<path:path_value>/', views.example_view), ]
  6. 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.

    python
    from 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.