Lesson 5 - Simple Template View
LEARN
Today's Agenda
- You know about Django projects
- Views
- URL Routes
- Templates
- Class-based views
- Pages app
- TemplateView
Class-based views
- Defines all of the view logic as a Python object class
- Override any behavior you wish
- TemplateView shows an HTML template as a view
- Design patterns for custom Django 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
- Mark-Seaman/BACS350
- Look at my code after you create your own
- You learn by doing - practice makes perfect
Exercise
- Start with my code
- Build a new view template, "profile.html"
- Create a URL route, "profile" that shows the view
- Add a home link to the page template
- Define the context for all pages to take you home
- Create template with HTML that validates