Configuring Django Templates

3 min read

Django is among the most recommended full stack web development frameworks at the moment. Django follows Model-Template-View (MTV) architecture. This is something similar to the traditional MVC( Model-View_Controller) architecture, but in Django, views are more like controllers, and MVC’s views are actually the template of Django.

Django templates define the layout and final formatting sent to end users after a view method is finished processing a request. MTV architecture lets Django sperate Python and HTML code which is necessary because at the moment browsers don't understand Python.

In this article, we will go through the configuration required for Django templates.

Configuring the Templates Directory

In order to use the  Django Template Language (DTL), we first need to make some configurations in our Django project.

Prerequisite:

Note: I am assuming you have one Django project up and running also I am working with the hello world project from the guide above.

Step 1

Inside your project directory, create a folder named templates.

├── db.sqlite3
├── hello_world_project
├── manage.py
└── my_app
└── templates

Step 2

Tell Django where the templates are housed in your settings.py create a variable named TEMPLATE_DIR under the BASE_DIR.

# Templates Directory
TEMPLATE_DIR = os.path.join(BASE_DIR,"templates")

This will yield an absolute path to the templates directory of our project irrespective of  OS. Using this method is effective because, On a POSIX-compatible operating system, forward slashes would be used to separate directories, whereas a Windows operating system would use backward slashes.

If you manually append slashes to paths, you may end up with path errors when attempting to run your code on a different operating system.

Step 3

In settings.py scroll to the TEMPLATES, which should look like this.

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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',
            ],
        },
    },
]

Now add the newly created TEMPLATE_DIRS  in the DIRS.

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        #  Add  'TEMPLATE_DIR' here
        'DIRS': [TEMPLATE_DIR],
        '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',
            ],
        },
    },
]

Now save and close the file we are done with the configurations.

Verifying By Creating A Template

Now that we have made all the essential configurations for the Django Template Language (DTL), it's time to create some templates.

In your templates folder create a file named index.html

<!DOCTYPE html>
<head>
    <title>My Awesome Site</title>
</head>
<body>
    <h1> Hello, This is from Index.html</h1>
    <h3>{{ insert_me }}</h3>
</body>
</html>

This is a basic HTML file the odd thing out here is the variable {{ insert_me }}, Any text surrounded is pair of curly braces is a variable in Django templates. We will see this variable in action just in a bit.

Open views.py of your app and make a view function for this variable.

from django.shortcuts import render

def index(request):
    my_dict = {"insert_me": "I am from views.py"}
    return render(request,'index.html',context=my_dict)

We are using the Django's built-in method render which acts as a bridge between static HTML and Python. The render function takes three required arguments render(requesttemplate_namecontext=None)

Next, map URL for this view in your projects urls.py file

from my_app import views

urlpatterns = [
    path('admin/', admin.site.urls),
    # configured the URL
    path('',views.index, name="homepage")
]

Save the files and run the server.

python manage.py runserver

If everything went well, you should see this in your browser.

Configuring Django Templates
Notice how that variable injected the string into the HTML, that's the advantage of Django templates they make HTML dynamic.


DJANGO

Latest Articles

Latest from djangocentral

Capturing Query Parameters of request.get in Django

In Django, the request object contains a variety of information about the current HTTP request, including the query parameters. Query parameters are a way to pass additional information in the URL and are used to filter or sort data. The request object p…
Read more →

2 min read

Understanding related_name in Django Models

In Django, related_name is an attribute that can be used to specify the name of the reverse relation from the related model back to the model that defines the relation. It is used to specify the name of the attribute that will be used to access the relat…
Read more →

2 min read