Loading, please wait...

A to Z Full Forms and Acronyms

How to map URL in Django

In this we will see the ability of using include() function form django.conf.urls

Mapping URLs in django

In this, we will see the ability to use include(): function form django.conf.urls  for mapping our URL in project url.py file  

This include() function allows us to look for a match using regular expressions and link back to our application own url.py file

Note:- we will have to manually add this urls.py file

firstly let's make our view, to make that we will add following to view.py file

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def index(request):
    return HttpResponse("<h1>HEALTH IS THE MOST <br> IMPORTANT THING</h1>")

now in your application folder (here we have taken first_app) add urls.py file and add the following commands 

from first_app import views
from django.urls import include,path
from django.conf.urls import url


urlpatterns = [
    path('', views.index, name='index')
]

So  we will add the following to the project’s url.py

from django.contrib import admin
from django.urls import path
from django.urls import include
from django.conf.urls import url
from first_app import views

urlpatterns = [
    path('', views.index, name='index'),
    path('first_app',include('first_app.urls')),
    path('admin/', admin.site.urls),
]

This would allow us to look for any URL  that has  the pattern like

www.domainname.com/first_app/...

If  we match that pattern the include() function will tell Django to look at the urls.py file inside the first_app folder

now in a terminal run following command 

python manage.py runserve

well Done!! you have successfully mapped URL from your application to project urls.py file 

A to Z Full Forms and Acronyms

Related Article