URL Routing maps a URL to a specific View function.
When a user visits a URL, Django checks the URL configuration and executes the corresponding View.
blog/urls.py
Create a new file named urls.py inside the blog application.
from django.urls import path
from . import views
urlpatterns = [
]
from django.urls import path
from . import views
urlpatterns = [
path('', views.home),
]
Open the project's main URL file and include the blog application's URLs.
BlogProject/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')),
]
path('', include('blog.urls'))
the root URL (/) is now handled by our application.
Therefore, Django's default welcome page is replaced by our own Home Page.
A View is a Python function that receives a request and returns a response.
blog/views.py
from django.http import HttpResponse
def home(request):
return HttpResponse("Welcome to Django")
from django.http import HttpResponse
def home(request):
return HttpResponse("Welcome to Django")
def about(request):
return HttpResponse("About Page")
from django.urls import path
from . import views
urlpatterns = [
path('', views.home),
path('about/', views.about),
]
http://127.0.0.1:8000/
http://127.0.0.1:8000/about/
HttpResponse is used to send a response from a View to the browser.
It is useful when we want to display simple text content.
blog/views.py
from django.http import HttpResponse
def home(request):
return HttpResponse("Welcome to Django")
from django.http import HttpResponse
def about(request):
return HttpResponse("<h1>About Us</h1>")
About Us
The render() function is used to display HTML pages from a View.
This is the most commonly used approach in Django applications.
blog
│
├── templates
│
└── views.py
blog/templates/home.html
<h1>Welcome To Django</h1>
<p>This page is rendered using render().</p>
from django.shortcuts import render
def home(request):
return render(request,'home.html')
http://127.0.0.1:8000/
return render(request,'home.html')
We do not need to write:
return render(request,'templates/home.html')
A real website contains multiple pages such as Home, About and Contact.
demo/templates/about.html
<h1>About Us</h1>
<p>Welcome to our About Page.</p>
demo/templates/contact.html
<h1>Contact Us</h1>
<p>Welcome to our Contact Page.</p>
from django.shortcuts import render
def home(request):
return render(request,'home.html')
def about(request):
return render(request,'about.html')
def contact(request):
return render(request,'contact.html')
from django.urls import path
from . import views
urlpatterns = [
path('', views.home),
path('about/', views.about),
path('contact/', views.contact),
]
http://127.0.0.1:8000/
http://127.0.0.1:8000/about/
http://127.0.0.1:8000/contact/