Home >>Django Tutorial >Django URL Mapping

Django URL Mapping

Django URL Mapping

Django is a web application framework so it gets the user request through URL locater and responds back. To handle the URL, django.urls module is used in this framework. It is done by editing the project url.py file (myproject/url.py).

Let's see the file urls.py of the project:

// urls.py


from django.contrib import admin  
from django.urls import path  
  
urlpatterns = [  
    path('admin/', admin.site.urls),  
]  

The path function takes the first parameter as a route of the string or regex type.

The view parameter is a view function that is used to return a response in the form of a template to the user.

Let's see an example that gets the user request and map that route to call view function:

  1. First, create a function hello in the views.py file and this will be mapped from the url.py file.

// views.py


from django.shortcuts import render    
# Create your views here.    
from django.http import HttpResponse, HttpResponseNotFound    
from django.views.decorators.http import require_http_methods    
@require_http_methods(["GET"])    
def hello(request):    
    return HttpResponse('<h1>This is Http GET request.</h1>')    

// urls.py


from django.contrib import admin    
from django.urls import path    
from myapp import views    
urlpatterns = [    
    path('admin/', admin.site.urls),    
    path('index/', views.index),    
    path('hello/',  views.hello),    
]  

Now, we have to start the server and enter localhost:8000/hello in the browser. This URL will be mapped into the list of URLs and then it will call the corresponding function from the views file.


No Sidebar ads