Debug School

rakesh kumar
rakesh kumar

Posted on

Routing regular expressions in django

In Django, the regular expressions (regex) can be used to define more complex URL patterns. Here are five different examples of using regular expressions in the URL routing scheme:

Matching Numeric IDs:

from django.urls import re_path
from .views import profile_view

urlpatterns = [
    re_path(r'^profile/(?P<id>\d+)/$', profile_view, name='profile'),
]
Enter fullscreen mode Exit fullscreen mode

In the above example, the URL pattern /profile// will match numeric IDs, such as /profile/123/ or /profile/456/. The captured ID parameter will be passed to the profile_view function.

Matching Slugs:

from django.urls import re_path
from .views import article_view

urlpatterns = [
    re_path(r'^article/(?P<slug>[-\w]+)/$', article_view, name='article'),
]
Enter fullscreen mode Exit fullscreen mode

In this example, the URL pattern /article// will match slugs consisting of letters, numbers, hyphens, and underscores. For example, /article/my-example-article/ or /article/another-article-123/. The captured slug parameter will be passed to the article_view function.

Matching UUIDs:

from django.urls import re_path
from .views import resource_view

urlpatterns = [
    re_path(r'^resource/(?P<uuid>[0-9a-fA-F-]+)/$', resource_view, name='resource'),
]
Enter fullscreen mode Exit fullscreen mode

This example demonstrates matching UUIDs in the URL pattern /resource//. The UUID parameter can contain hexadecimal characters and hyphens. For example, /resource/123e4567-e89b-12d3-a456-426614174000/. The captured UUID parameter will be passed to the resource_view function.

Matching Date Formats:

from django.urls import re_path
from .views import event_view

urlpatterns = [
    re_path(r'^event/(?P<date>\d{4}-\d{2}-\d{2})/$', event_view, name='event'),
]
Enter fullscreen mode Exit fullscreen mode

This example matches date formats in the URL pattern /event//. The date parameter should follow the format YYYY-MM-DD. For example, /event/2022-01-01/ or /event/2023-12-31/. The captured date parameter will be passed to the event_view function.

Matching Multiple Parameters:

from django.urls import re_path
from .views import search_view

urlpatterns = [
    re_path(r'^search/(?P<category>\w+)/(?P<query>\w+)/$', search_view, name='search'),
]
Enter fullscreen mode Exit fullscreen mode

This example demonstrates matching multiple parameters in the URL pattern /search///. Both the category and query parameters can contain alphanumeric characters and underscores. For example, /search/books/programming/ or /search/movies/comedy/. The captured parameters will be passed to the search_view function.

Top comments (0)