How To Use Templates In Django

How To Use Templates In Django

Django is a web framework so, It needs to maintain the code in such a way that it should be easy to navigate and easy to read and maintain. As we already know the Django framework is a MVC, we do not write the HTML code in the views.py instead we write it in a template. In django web framework we generate dynamic HTTP response. While generating the dynamic HTML content we use a special syntax called "django template syntax". It will make the process easy for us. Before using the templates in our django project we need to configure some settings. Let's use templates in django by configuring template settings.

Django Template Settings Configuration:

  • myproject/settings.py
# .....
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates',],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

# ..... 
  • project structure
myproject
    ├── db.sqlite3
    ├── manage.py
    ├── myapp
    │   ├── admin.py
    │   ├── apps.py
    │   ├── __init__.py
    │   ├── migrations
    │   │   └── __init__.py
    │   ├── models.py
    │   ├── tests.py
    │   └── views.py
    ├── myproject
    │   ├── __init__.py
    │   ├── settings.py
    │   ├── urls.py
    │   └── wsgi.py
    └── templates
        └── home.html
  • myapp/views.py
from django.shortcuts import render

def home(request):
    return render(request, 'home.html')
  • myproject/urls.py
from django.urls import path
from myapp import views

urlpatterns = [
    path('', views.home, name='home'),
]
  • templates/home.html
<html>
  <title>Hello World</title>
  <body>
      <h1>Hello World</h1>
  </body>
</html>

Open settings.py file, you can find "TEMPLATE" setting. It contains list of settings for templates. Every template setting is dictionary object. It contains settings like BACKEND , DIRS, APP_DIRS, OPTIONS.
In Django we render the template using the the function*"render"to generate the dynamic HTML content. The *"render" function takes 3 parameters request, template_name and a context(a dictionary of keys and values which will be used inside the template). Before rendering the template Django looks for the template using its name. It searches for the template using its in "DIRS" setting for external templates. So, in the above code we have added "templates" directory. After adding the directory our project structure looks like above. When Django looks for the template It will find it in "templates" direcory that we have added.

Now, access the url localhost:8000 in your browser you can see the HTTP response "Hello World". We have simply rendered a static html. But, what we discussed is we generate a dynamic response using django web framework. Let's see how we can generate a dynamic response in Django.

Let's change the views.py and home.html as follows

  • myapp/views.py
from django.shortcuts import render

def home(request):
    context = {'name': 'Anjaneyulu Batta'}
    return render(request, 'home.html', context)
  • templates/home.html
<html>
  <title>Hello {{ name }}</title>
  <body>
      <h1>Hello {{ name }}</h1>
  </body>
</html>

Now, access the url localhost:8000 in your browser you can see the HTTP response "Hello Anjaneyulu Batta". In the view we have passed the context dictionary and accessed the value with key name in the template using the django template syntax "{{ name }}". In this way we can make use of django templates.

Reference: https://docs.djangoproject.com/en/dev/topics/templates/