Debug School

rakesh kumar
rakesh kumar

Posted on

Routing scheme in django

In Django, there are several routing schemes that can be used to define URL patterns and map them to view functions or class-based views. Here are some of the commonly used routing schemes in Django:

Simple Route:
The simplest routing scheme in Django is the path function, which maps a URL pattern to a view function. It is used to define basic URL patterns. Here's an example:

from django.urls import path
from .views import home_view

urlpatterns = [
    path('', home_view, name='home'),
]
Enter fullscreen mode Exit fullscreen mode

In the above example, the root URL (/) is mapped to the home_view function.

Route with Parameters:
Django allows you to define URL patterns with parameters using angle brackets (< >). These parameters capture specific parts of the URL and pass them as arguments to the view function. Here's an example:

from django.urls import path
from .views import user_profile_view

urlpatterns = [
    path('profile/<int:user_id>/', user_profile_view, name='profile'),
]
Enter fullscreen mode Exit fullscreen mode

In the above example, the URL pattern /profile// maps to the user_profile_view function, where the user_id parameter is passed as an argument.

Route with Regular Expressions:
Django supports regular expressions for more complex URL patterns. You can use the re_path function to define routes using regular expressions. Here's an example:

from django.urls import re_path
from .views import article_view

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

the above example, the URL pattern /article// is defined using a regular expression. The captured slug parameter is passed to the article_view function.

Include Function:
The include function allows you to include URLs from other URL configuration files. This is useful for organizing your URL patterns into modular apps. Here's an example:

from django.urls import include, path

urlpatterns = [
    path('blog/', include('blog.urls')),
]
Enter fullscreen mode Exit fullscreen mode

In the above example, all the URL patterns defined in the blog.urls module will be included under the /blog/ prefix.

These are just a few examples of the different routing schemes available in Django. You can mix and match these routing schemes to define complex URL patterns that match your application's requirements.

Top comments (0)