This article is the 6th installment of the Django Class-Based Views (CBV) exploration series, discussing how to automate simple page rendering and redirect handling with TemplateView and RedirectView. In the previous post (5th installment), we built CRUD using CreateView
, UpdateView
, and DeleteView
. This time, we will explore how to efficiently set up lighter pages and redirect handling.
To go back to the previous installment, click the link below!
Implementing CRUD with CreateView, UpdateView, and DeleteView
“Easily automate simple page structures and redirections with Django TemplateView and RedirectView!”
1. Why are TemplateView & RedirectView Necessary?
TemplateView and RedirectView are class-based views specialized for the simplest use cases in Django (Generic Views).
-
TemplateView
-
It is useful when passing a static page or simple context to the template without any special data processing logic.
-
Examples: “About” page, “FAQ” page, error pages like 404/500 (when configured separately), etc.
-
-
RedirectView
-
Used to immediately redirect to a specific URL.
-
Examples: Redirecting to a specific page when accessing the domain root (
/
), simple shortened URL services, promotional redirects for campaigns, etc.
-
Both focus on handling simple page processes without requiring database manipulation or form validation, making them different from previously discussed views like FormView
and CreateView
.
2. How to Use TemplateView
2.1 Basic Structure
# views.py
from django.views.generic import TemplateView
class HomePageView(TemplateView):
template_name = 'home.html'
-
template_name
: Specifies the path to the template file to be rendered. -
Even without overriding the
get()
method, it automatically renders the template specified intemplate_name
for GET requests.
2.2 Connecting to urls.py
# urls.py
from django.urls import path
from .views import HomePageView
urlpatterns = [
path('', HomePageView.as_view(), name='home'),
]
- When accessed via the root URL (
""
), thehome.html
template will be displayed.
2.3 Template Example: home.html
<!DOCTYPE html>
<html>
<head>
<title>Homepage</title>
</head>
<body>
<h1>Hello! Welcome to the homepage.</h1>
</body>
</html>
3. Passing Context Data in TemplateView
In addition to simple template rendering, if you want to pass simple variables to the template, you should override the get_context_data()
method.
from django.views.generic import TemplateView
class AboutPageView(TemplateView):
template_name = 'about.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['page_title'] = 'About Us'
context['description'] = 'This site is an example to introduce Django CBV.'
return context
Then you can use the variables page_title
and description
in the template:
<!-- about.html -->
<!DOCTYPE html>
<html>
<head>
<title>{{ page_title }}</title>
</head>
<body>
<h1>{{ page_title }}</h1>
<p>{{ description }}</p>
</body>
</html>
Tip:
TemplateView is particularly useful for creating simple pages that do not require DB queries, and
If multiple templates need common variables, consider using a Mixin or combining with a base template.
4. How to Use RedirectView
4.1 Basic Structure
# views.py
from django.views.generic import RedirectView
class BlogRedirectView(RedirectView):
pattern_name = 'blog_list' # URL name
# (Optional) Can specify parameters needed for URL reversing
# query_string = True # Whether to maintain query string
# permanent = False # Whether it's a permanent redirect (301 vs 302)
-
pattern_name
: By specifying the URL name (for example,'blog_list'
) fromurls.py
, it redirects to that path when the view is executed. -
If set to
permanent=True
, it performs a permanent redirect (301); if set to the default (False
), it performs a temporary redirect (302). -
Setting
query_string=True
will append the original URL's query string (like?page=2
) to the redirect target URL.
4.2 Connecting to urls.py
# urls.py
from django.urls import path
from .views import BlogRedirectView, HomePageView
urlpatterns = [
path('go-to-blog/', BlogRedirectView.as_view(), name='go_to_blog'),
path('', HomePageView.as_view(), name='home'),
]
- Accessing
/go-to-blog/
will redirect to the URL pattern specified as'blog_list'
.
4.3 Directly Specifying the URL
You can also directly place an absolute path or an external link in the url
attribute instead of the URL name.
class ExternalRedirectView(RedirectView):
url = 'https://www.djangoproject.com/'
urlpatterns = [
path('django-home/', ExternalRedirectView.as_view(), name='django_home'),
]
- Doing this will redirect from
/django-home/
tohttps://www.djangoproject.com/
.
5. Examples of Using TemplateView & RedirectView
-
Notice Page: You can use
TemplateView
to display a static page with fixed notice content without database integration. -
FAQ / ‘Coming Soon’ Page: Quick launch of product FAQs or maintenance pages is also useful.
-
Domain Root Redirect: You can automate simple redirect logic like “when accessing the main page, redirect to /home/” with
RedirectView
. -
Connecting External Service Links: Like a shortened URL, it is also good for redirecting to external sites when accessing specific paths.
6. Comparing with FBV
Feature | FBV (Function-Based View) | TemplateView / RedirectView (Class-Based View) |
---|---|---|
Static page rendering (e.g., FAQ) | def faq(request): return render(request, 'faq.html') etc., written directly |
TemplateView: Just specify template_name for automatic page rendering |
Simple redirection | return redirect('some_url') / HttpResponseRedirect(...) used |
RedirectView: Just specify the URL or pattern_name |
Additional context transmission | Each time context = {...} -> render(...) done manually |
Can be managed structurally and consistently through get_context_data() |
Code structure / Maintainability | Short pages or simple redirects are okay with FBV, but duplications arise with many static pages or redirects | “Necessary settings are separated as properties or methods,” making maintenance easier |
Developer productivity (key advantages) | “Directly using render, redirect functions –> possibility of duplication” | “Time-saving, Code consistency, Maintainability (Productivity boost)” |
7. Conclusion and Preview of Next Installment
TemplateView and RedirectView are class-based views that help manage the simplest page processing easily in Django projects.
When complex logic like DB integration or form validation is not required, using these views can reduce duplicate code and keep the project structure much cleaner.
Now we can implement most of the essential elements of web development with CBVs including “static pages,” “redirects,” “CRUD (Create/Update/Delete),” “list/detail views,” and “form processing.”
In the next installment (series 7), we will introduce how to effectively reuse common functionalities using the Mixin commonly used in Django and efficiently implement permission management and login checks.
Revisit Previous Posts
- Class-Based Views (CBV) Exploration Series #1 – The Reason for Moving from FBV to CBV and Developer Mindset
- Class-Based Views (CBV) Exploration Series #2 – Understanding Django's Basic View Class
- Class-Based Views (CBV) Exploration Series #3 – Simplifying Form Processing with FormView
- Class-Based Views (CBV) Exploration Series #4 – How to Use ListView & DetailView
- Class-Based Views (CBV) Exploration Series #5 – Implementing CRUD with CreateView, UpdateView, and DeleteView
“Automate cumbersome static page handling and redirection with TemplateView and RedirectView, making your projects more concise and productive!”
There are no comments.