Saturday, July 10, 2021

django - how to use templates

 Step1: Open settings.py and write templates in the DIR of template section as below:


Step2: Create a templates folder and create a index.html file in it as below:

Contents of index.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>template is working</title>
</head>
<body>
<h1>from index page, Hello</h1>
</body>
</html>

Step3: in the views.py, import the render module from shortcuts and call the template as below:

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

def index(request):
# return HttpResponse("Hello")
return render(request,'index.html')

def about(request):
return HttpResponse("<h1>about</h1>")

The server will run automatically:

You can also create a dictionary and send the same to the template while rendering from views.py and use them in the tempate.

views.py:

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

def index(request):
params = {"name":"Sri","role":"develoepr"}
# return HttpResponse("Hello")
return render(request,'index.html',params)


template - index.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>template is working</title>
</head>
<body>
<h1>from index page, Hello</h1>
{{name}}
</body>
</html>


web page:






No comments:

Post a Comment

Featured Post

11g to 12c OSB projects migration points

1. Export 11g OSB code and import in 12c Jdeveloper. Steps to import OSB project in Jdeveloper:   File⇾Import⇾Service Bus Resources⇾ Se...