Django template view


template view

  • It's simple view to display simple html page with/without using the context.
  • we will be using the code from Create django app
  • create a template templates/my_template.html
  • we will be using the below template in the view


<!DOCTYPE html>
<html lang="en">
  <title>{{ title }}</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="">
  <script src=""></script>
  <script src=""></script>
  <div class="jumbotron text-center">
    <p>Resize this responsive page to see the effect!</p> 

function based template view

  • open my_app/ and add below code to it.


from django.shortcuts import render

def my_template_view(request):
    context = {"title": "Simple template view"}
    return render(request, "my_template.html", context)

class based template view

  • Django comes with generic reusable views.
  • Lets use TemplateVeiew
from django.views.generic import TemplateView

# ...
class MyTemplateView(TemplateView):
    template_name = "my_template.html"

    def get_context_data(self):
      context = {"title": "Simple template view"}
      return context

configure urls

  • open my_app/ and add below code to it.
from django.urls import path
from my_app import views

urlpatterns = [
    # ...
    path('fbv_template_view', views.my_template_view, name='my_template_view'),
    path('cbv_template_view', views.MyTemplateView.as_view(), name='my_template_view'),
    # ...