UNC BACS 350

Web Apps with Python/Django

Logo

Lesson 5 - Simple Template View

LEARN

Today's Agenda

Class-based views

BUILD

Template View in URLs

urls.py

from django.urls import path
from django.views.generic import TemplateView

urlpatterns = [
    path('about', TemplateView.as_view(template_name="about.html")),
    path('home', TemplateView.as_view(template_name="home.html")),
]

templates/about.html

<h1>About</h1>
<a href="home">GO HOME</a>

Add a new app

python manage.py startapp pages

Add Custom Django Views

pages/views.py

from django.views.generic import TemplateView

class AboutView(TemplateView):
    template_name = 'about.html'

class HomeView(TemplateView):
    template_name = "home.html"

urls.py

from django.urls import path
from django.views.generic import AboutView, HomeView

urlpatterns = [
    path('about', AboutView.as_view()),
    path('home', HomeView.as_view()),
]

Add Data to Django Views

templates/page.html

<h1>{{ title }}</h1>
<p>
    {{ body}}
</p>

Data as dictionary

Define what goes in the variable slots

{
    'title': 'My Home Page', 
    'body': 'This page is boring ...',
}

Setting View Context

pages/views.py

 class AboutView(TemplateView):
    template_name = 'page.html'

    def get_context_data(self, **kwargs):
        return {
            'title': 'About this Class', 
            'body': 'Once upon a time ...',
        }

 class HomeView(TemplateView):
    template_name = "page.html"

    def get_context_data(self, **kwargs):
        return {
            'title': 'My Home Page', 
            'body': 'This page is boring ...',
        }

Demo Code in Github

Exercise