django
  1. django-url-mapping

Basics of Django

Heading h1

URL Mapping

Syntax

from django.urls import path
from . import views

urlpatterns = [
    path('url-path/', views.viewFunction, name='view-name'),
]

Example

from django.urls import path
from . import views

urlpatterns = [
    path('home/', views.home, name='home'),
    path('about/', views.about, name='about'),
    path('contact/', views.contact, name='contact'),
]

Output

The code above maps the following URLs to specific views functions:

  • /home/ => calls the views.home function
  • /about/ => calls the views.about function
  • /contact/ => calls the views.contact function

Explanation

URL Mapping in Django means mapping a specific URL pattern to a view function. This helps the Django application to route requests to the corresponding view function for that URL.

In the code example, path() function from Django's urls module defines a URL pattern as the first argument, followed by the view function that is called when the URL is accessed.

The name argument is used to specify a unique name for the URL pattern, which can be used to reference the URL pattern in other parts of the Django application.

Use

URL Mapping is an essential component of Django that allows you to route requests from browsers to specific view functions that can handle those requests. It helps in building a well-organized and scalable Django application.

Important Points

  • URL Mapping is essential to route requests to the corresponding view function for a specific URL pattern.
  • Django's path() function is used to define URL patterns and view functions.
  • The name argument is used to specify a unique name for a URL pattern.
  • URL Mapping plays a crucial role in building a scalable and structured Django web application.

Summary

URL Mapping in Django allows mapping HTTP requests to view functions that can handle those requests. It is a fundamental aspect of building web applications that require routing. In the present example, we learned how to define URL patterns in Django and how to map URLs to view functions that handle those requests. It is an essential component to build scalable and organized Django applications.

Published on: