Django Templates

 

Templates are the third and most important part of Django’s MVT Structure. A template in Django is basically written in HTML, CSS, and Javascript in a .html file. Django framework efficiently handles and generates dynamically HTML web pages that are visible to the end-user. Django mainly functions with a backend so, in order to provide a frontend and provide a layout to our website, we use templates. There are two methods of adding the template to our website depending on our needs.

 

  • We can use a single template directory which will be spread over the entire project.
  • For each app of our project, we can create a different template directory.

 

For our current project, we will create a single template directory that will be spread over the entire project for simplicity. App-level templates are generally used in big projects or in case we want to provide a different layout to each component of our webpage.

 

Now let’s create the templates directory and add that directory to our settings.py file.

 

 

Adding this templates folder to our settings.py file – 

 

Python3




TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
       
        # adding template folder that we just created
        'DIRS': [BASE_DIR/'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',
            ],
        },
    },
]


After adding the location of the template directory we will create a simple HTML file and name it as home.html and then we will render this file from our view function.

HTML file:

HTML




<h1>Welcome to w3wiki</h1>


 
 

To render this HTML on our site we need to use the render function from the django.shortcuts. Below is the updated view function.

 

views.py

 

Python3




from django.http import HttpResponse
from django.shortcuts import render
 
def home(request):
 
    context = {}
    return render(request, 'home.html', context)


 
 

If we head to our website we will see the HTML data on our site as –

 

 

After learning about the views, URLs, and templates let’s see how to show the data from our database to our home page.

 

First, we need to update our views.py file to get the data from our database. Here, we will use class based views for our project.

 

views.py

 

Python3




from .models import Post
from django.views.generic import ListView
 
class HomeView(ListView):
    model = Post
    template_name = 'home.html'


 
 

The above code is similar to –

 

Python3




def home(request):
    posts = Post.objects.all()
    context = {
        'Posts': posts
    }
 
    return render(request, 'home.html', context)


 
 

Now for class based views we also need to make changes to the urls.py file. See the below code – 

 

Python3




from django.urls import path
# from . import views
from .views import HomeView
 
urlpatterns = [
    path('', HomeView.as_view(), name='home'),
]


 
 

Here as_view() function is used to make class HomeView as a view function. Now finally we need to make changes to the home.html file.

 

HTML




{% for post in object_list %}
    <h1>{{post.title}}</h1>
    <small>By: {{post.author.first_name}} {{post.author.last_name}}</small>
     
 
<p>{{post.body}}</p>
 
 
{% endfor %}


 
 

In the above HTML file object_list is the context variable which contains the list of all the objects of the model which is specified in the HomeView class. Now when we head to http://127.0.0.1:8000/ we will see something like this – 

 

Note: Make sure to add first name and last name for the superuser from the admin panel.

 

 

Let’s add some more post from the admin panel and see whether they gets render to our site or not. 

 

Getting started with Django

Python Django is a web framework that is used to create web applications very efficiently and quickly. Django is called a battery included framework because it contains a lot of in-built features such as Django Admin Interface, default database – SQLite3, etc. Django provides various ready-made components such as a way to handle user authentication, a management panel for your website, forms, a way to upload files, etc.

In this article, we will learn Django by creating a basic blogging web application.  

Similar Reads

Why Django Framework?

Django is a rapid web development framework that can be used to develop fully fleshed web applications in a short period of time. It’s very easy to switch databases in the Django framework. It has a built-in admin interface which makes it easy to work with it. Django is a fully functional framework that requires nothing else. It has thousands of additional packages available. It is very scalable....

Structure of Django Web Application

Django is based on MVT (Model-View-Template) architecture. MVT is a software design pattern for developing a web application....

Setting the Development Environment

It is always advisable to use a virtual environment before starting any Django project because sometimes when you are working on multiple projects you might need different versions of Django. The virtual environment creates a separate environment for different projects and you can install dependencies of each project separately. To create a virtual environment type the below command in the terminal –...

Installing Django

We can install Django using the pip command. To install this type the below command in the terminal....

Starting the Project

To initiate a project of Django on Your PC, open Terminal and Enter the following command...

Project Structure

A Django Project when initialized contains basic files by default such as manage.py, view.py, etc. A simple project structure is enough to create a single-page application. Here are the major files and their explanations. Inside the geeks_site folder ( project folder ) there will be the following files-...

Creating App

Till now we have created the Django project and now we will create an app. Django is famous for its unique and fully managed app structure. For every functionality, an app can be created like a completely independent module. To create an app we need to go to the directory containing manage.py and run the following command –...

Defining Models

...

Render Model in Django Admin

...

Django Views

...

Django URL Patterns

...

Django Templates

...

Styling Project

After creating and adding data to our models, we need to display the data to our site. Rendering data is a two-step process. First we need to create our view function and then we need to pass the data to our template. Here we will focus on the view function....

Django Forms

...

Django Projects

...