Django Template implementation process (Part I)

Project setup

django-admin startproject hello_world
python3 manage.py runserver
Starter Django webpage

Creating the first Template

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <meta http-equiv="X-UA-Compatible" content="IE=edge">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <title>Document</title></head><body>    Hello World</body></html>
from django.http import HttpResponsefrom django.template import Template, Contextdef first_template(self):  html_path = open(‘/Users/octaviolafourcade/Documents/PYTHON/django/hello_world/hello_world/templates/first_template.html’)  template = Template(html_path.read())  html_path.close()  context = Context()  document = template.render(context)  return HttpResponse(document)
from django.contrib import adminfrom django.urls import pathfrom hello_world.views import first_templateurlpatterns = [  path('admin/', admin.site.urls),  path('first_template/', first_template),]

Improving the template

from django.http import HttpResponsefrom django.template import Template, Contextdef first_template(self):    name = 'John'    last_name = 'Doe'    dictionary = {'name': name, 'last_name': last_name}    html_path = open('/Users/octaviolafourcade/Documents/PYTHON/django/hello_world/hello_world/templates/first_template.html')    template = Template(html_path.read())    html_path.close()    context = Context(dictionary)    document = template.render(context)    return HttpResponse(document)
<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <meta http-equiv="X-UA-Compatible" content="IE=edge">  <meta name="viewport" content="width=device-width, initial-scale=1.0">  <title>Document</title></head><body>  <h1>Hello World</h1>  <br>  <p style="color: red">My name is {{name}}</p>  <p style="color: blue">My last name is {{last_name}}</p></body></html>

Template loaders

from django.template import loader
'DIRS': ['/Users/octaviolafourcade/Documents/PYTHON/django/hello_world/hello_world/templates/'],
from django.http import HttpResponsefrom django.template import Template, Context, loaderdef first_template(self):  name = 'John'  last_name = 'Doe'  dictionary = {'name': name, 'last_name': last_name}  template = loader.get_template('first_template.html')  document = template.render(dictionary)  return HttpResponse(document)

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store