We are going to explore how to render the HTML templates in Django using Templates folder. Django is written in Python and is different than how things work in say PHP for example. In PHP we can mix PHP with HTML to output web pages. Django and Python work a little differently. In Django, we use the Django Template Language or DTL templates . Django give Output dynamic data generated by Python and Django into HTML pages. In the prior tutorial, we skipped using templates and simply returned HTTP responses directly from view functions. Now we are going to see how to use a view function to render a template.
Adding Templates folder
As first step first we need to create templates folder and this is going to be templates directory. This is the main folder where we place our whole files and access the code files from this folder.
configure templates settings
To render the HTML pages from the created templates folder . We need to configure the path settings for the templates folder.
To configure path first we need to go to project/settings.py and configure the templates location. Refer the below code for updating path.
Creation of HTML pages
In templates folder add the HTML pages file with .html extension and we will render the particular page when the view function used.
Inside home.py file we write the following code (the code user specific).
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>example</title> </head> <body> <h1> this is an example project</h1> <p>this is an example paragraph</p> </body> </html>
updating Views folder to render HTML page
the project/views.py folder is the main folder where this folder will help in sending the control from main file to templates folder to render the web pages.
We use render function which used to render the web pages when the specific function called and we pass two arguments inside the render function.
from django.shortcuts import render # Create your views here. def saikumarpages(request): return render(request,'home.html')
Updating urls.py file
the project/views.py folder is the main folder where this folder will help in routing the control to views.py file.
from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('', include('sai.urls')), ]
This is the git repository project link —