Template view

Template view

Template view: Django offers us various built in functionalities, one of them is Class Based Views(CBV). Django’s CBVs explores our experience with Object Oriented Programming very well. In our last session we have simply discussed about Class Based Views. In this tutorial, we will discuss about displaying templates using these Class Based Views i.e. Template view.

If you want to get basic idea about Django’s Class Based Views, then you can visit the link below:

Django Class Based Views

Function Based Views vs Class Based views(Calling template)

In our previous article, we was just discussed about returning a plain text. But now it is time to learn how to return a template using the same. Now we are going to learn how to use TemplateView that comes with Django. Here is the simple comparison between using a function to call a template versus the TemplateView!

Template view
Template view
  • As you can see above, there is a little difference to call an HTML page using simple functional view and class based views.
  • Above, left side is a functional view and right side is a view with built in TemplateView
  • As you can see, TemplateView is a parent class of IndexView
  • Let’s discuss of creating a class using TemplateView in detail.

Template view example

Now it is time to perform all above discussed. For this, i will use my previous project named CBV, here is the folder tree for the same:

What we will do next?

  1. Add template folder inside root directory.
  2. Create view which returns HTML page.
  3. Create template for that view
  4. Don’t forget to setup URL file.
  5. Run server and check output.
Django Class Based Views
Django Class Based Views

Step 1: Add template folder inside root directory

Here i expect from your side to add Template directory to project’s settings.py file. If you don’t know how to do don’t worry you can download code from below and see settings.py file. (Otherwise an error will occur i.e. “Template Does not exist”)

CBV > CBV > settings.py

  • Create template folder inside root directory i.e. CBV > templates
  • Set path for that folder:
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        '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',
            ],
        },
    },
]

Step 2: Create view which returns HTML page

CBV > cbvapp > views.py

from django.shortcuts import render
from django.views.generic import View,TemplateView

class MyCBV(TemplateView):
    template_name= 'index.html'

Step 3: Create Template for that view

  • Create HTML file with name you specified in views.py. Here the name is ‘index.html’.
  • Save this file inside template folder that we just configured
  • Here is the code inside my index.html file

CBV > templates > index.html

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
    <title></title>
  </head>
  <body>
    <div class="container-fluid">
      <div class="row" style='height:400px;background:url("http://www.compassproperties.com/wp-content/uploads/2018/02/city-square2.jpg");background-size:100% 100%;'>
        <div class="col-md-12 px-0">
          <section>
            <h1 class='bg-dark text-light py-1'>Logo Here</h1>
            <nav class='navbar navbar-expand navbar-dark fixed-top' style='background:rgba(0,0,0,0.5);'>
              <ul class='navbar-nav mx-auto'>
                <li class='nav-item'>
                  <a href="#" class='nav-link'>Home</a>
                </li>
                <li class='nav-item'>
                  <a href="#" class='nav-link'>About</a>
                </li>
                <li class='nav-item'>
                  <a href="#" class='nav-link'>Contact</a>
                </li>
              </ul>
            </nav>
            <div class="text-center text-white pt-5">
              <h1 class='display-1'><strong>It is awesome</strong> </h1>
              <p class=''>It is a paragraph</p>
            </div>
          </section>
        </div>
      </div>
      <div class="row">
        <div class="col-md-12 my-5 text-center text-warning">
          <h1>Who we are</h1>
        </div>
        <div class="col-md-12">
          <div class="row">
            <div class="col-md-4">
              <p>This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.</p>
            </div>
            <div class="col-md-4">
              <p>This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.</p>

            </div>
            <div class="col-md-4">
              <p>This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.</p>

            </div>
          </div>
        </div>
      </div>
    </div>
  </body>
</html>

Step 4: Don’t forget to setup url file for that view

CBV > CBV > urls.py

from django.contrib import admin
from django.urls import path
from cbvapp import views
urlpatterns = [
    path('',views.MyCBV.as_view()),
    path('admin/', admin.site.urls),
]

Step 5: Run server and see the output

Check output using pyhton manage.py runserver. Here is the output page for the above code:

Template view
Template view

Use a Template CBV along with a context dictionary

You can also inject content inside the HTML page using a context dictionary. Here is a code to inject(send something) from views to templates:

CBV > cbvapp > views.py

from django.shortcuts import render
from django.views.generic import View,TemplateView

class MyCBV(TemplateView):
    template_name= 'index.html'

    def get_context_data(self,**kwargs):
        data = super().get_context_data(**kwargs)
        data['var1'] = "I am data variable 1"
        data['var2'] =100
        return data

CBV > templates > index.html

  • I just have added context dictionary variable to the previous page.
  • Here is the code that i just added.
<h1 class='alert alert-success'>
    {{ var1 }}<br/>
    {{ var2 }}
 </h1>

Output

Template view
Template view

Download source code

Download project on Github
Download project on Github 

So, it is all about Template view. We will discuss more about that in our further tutorials. Thanks!!!

8 thoughts on “Template view

Leave a Reply

Your email address will not be published. Required fields are marked *

  1. Hi would you mind letting me know which web host you’re utilizing? I’ve loaded your blog in 3 different web browsers and I must say this blog loads a lot faster then most. Can you recommend a good internet hosting provider at a honest price? Thank you, I appreciate it!

  2. I simply want to mention I am very new to blogging and certainly savored your blog site. Very likely I’m want to bookmark your site . You certainly come with superb writings. Thanks a bunch for revealing your blog.

  3. You decided not to enter into great detail, nevertheless, you presented the essentials I desired to get me through. If you are trying to find started out with a task this is often the type of details that’s needed. Having more writers be part of the dialogue might be a great thing.

  4. I think this is among the most significant info for me. And i’m glad reading your article. But wanna remark on some general things, The site style is great, the articles is really great : D. Good job, cheers

  5. Absolutely NEW update of captchas solving package “XRumer 16.0 + XEvil 4.0”:
    captchas recognition of Google (ReCaptcha-2 and ReCaptcha-3), Facebook, BitFinex, Bing, Hotmail, SolveMedia, Yandex,
    and more than 8400 another subtypes of captchas,
    with highest precision (80..100%) and highest speed (100 img per second).
    You can use XEvil 4.0 with any most popular SEO/SMM programms: iMacros, XRumer, GSA SER, ZennoPoster, Srapebox, Senuke, and more than 100 of other software.

    Interested? You can find a lot of introducing videos about XEvil in YouTube.

    FREE DEMO AVAILABLE!

    Good luck 😉

  6. Perfect update of captcha solution software “XEvil 4.0”:
    captchas solution of Google (ReCaptcha-2 and ReCaptcha-3), Facebook, BitFinex, Bing, Hotmail, SolveMedia, Yandex,
    and more than 8400 another types of captchas,
    with highest precision (80..100%) and highest speed (100 img per second).
    You can use XEvil 4.0 with any most popular SEO/SMM software: iMacros, XRumer, GSA SER, ZennoPoster, Srapebox, Senuke, and more than 100 of other software.

    Interested? You can find a lot of impessive videos about XEvil in YouTube.

    FREE DEMO AVAILABLE!

    Good luck 😉

Please wait...

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.