Skip to main content
Django Basics Tutorial
CHAPTER 07 Beginner

Django Views and Templates

Updated: May 14, 2026
30 min read

# CHAPTER 7

Django Views and Templates

1. Introduction

While HttpResponse("<h1>Hello</h1>") proves our routing works, no professional developer writes HTML inside a Python string. It is unmaintainable and violates the MVT architecture. We must separate the presentation (HTML) from the logic (Python). In this chapter, we will learn how to use the render() function to send actual HTML files to the browser, how to pass dynamic Python variables into those files, and how to use Django's powerful Template Inheritance system to avoid writing duplicate code.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Use the render() function in a View to return an HTML file.
  • Pass a Python dictionary (Context) to a Template.
  • Utilize Django Template Tags ({{ }} and {% %}).
  • Implement Template Inheritance using extends and block.

3. Beginner-Friendly Explanation

Imagine writing a standard HTML website with 50 pages. Every single page requires the exact same <nav> bar and <footer>. If the company logo changes, you have to manually open 50 HTML files and change the image link. This is a nightmare. Django Templates solve this using *Inheritance*. You build one "Master Skeleton" (base.html) containing the nav and footer. Then, you build a "Child" (home.html) that only contains the unique homepage content. The child tells Django: "Grab the Master Skeleton, and just stuff my unique content into the middle of it." If the logo changes, you change it once in the Master Skeleton, and all 50 pages update instantly!

4. Step 1: Creating the Templates Folder

Django expects HTML files to live in a very specific location. Inside your blog app, create a folder named templates. Inside templates, create another folder named blog. *(Yes, it is blog/templates/blog/. This nested structure prevents Django from getting confused if multiple apps have a file named home.html).*

5. Step 2: Rendering an HTML File

Create blog/templates/blog/home.html:
html
1234567
<!DOCTYPE html>
<html>
<head><title>My Django Blog</title></head>
<body>
    <h1>Welcome to the Blog Homepage</h1>
</body>
</html>

Now, update blog/views.py to use render instead of HttpResponse:

python
12345
from django.shortcuts import render

def home(request):
    # render() takes the request, the template path, and optional data
    return render(request, &#039;blog/home.html')

*Refresh your browser. You are now seeing an actual HTML file!*

6. Step 3: Passing Dynamic Data (Context)

Let's pass a Python list of dictionaries (simulating database posts) to the HTML file.

In views.py:

python
123456789101112131415
def home(request):
    # Simulated Data
    posts = [
        {&#039;title': 'First Post', 'author': 'Alice', 'date': 'Oct 1'},
        {&#039;title': 'Second Post', 'author': 'Bob', 'date': 'Oct 2'},
    ]
    
    # Package data into a dictionary called 'context'
    context = {
        &#039;posts': posts,
        &#039;page_title': "Home"
    }
    
    # Pass the context to the template
    return render(request, &#039;blog/home.html', context)

7. Step 4: Django Template Tags

HTML doesn't understand Python. Django provides special tags to bridge the gap.
  • {{ variable }}: Inject a variable directly into the page.
  • {% logic %}: Run a Python for loop or if statement.

In home.html:

html
123456789
<h1>{{ page_title }}</h1>

<!-- Loop through the Python list -->
{% for post in posts %}
    <div class="post">
        <h2>{{ post.title }}</h2>
        <p>By {{ post.author }} on {{ post.date }}</p>
    </div>
{% endfor %}

*Django processes the loop, generates the pure HTML, and sends it to the browser.*

8. Step 5: Template Inheritance

Create the Master Skeleton: blog/templates/blog/base.html
html
1234567891011121314
<!DOCTYPE html>
<html>
<body>
    <nav>
        <a href="/">Home</a> | <a href="/about">About</a>
    </nav>
    
    <!-- This is a placeholder! Child templates will inject data here -->
    {% block content %}
    {% endblock %}
    
    <footer>Copyright 2026</footer>
</body>
</html>

Rewrite the Child: blog/templates/blog/home.html

html
12345678910
<!-- 1. Inherit from the Master Skeleton -->
{% extends "blog/base.html" %}

<!-- 2. Target the specific placeholder block -->
{% block content %}
    <h1>{{ page_title }}</h1>
    {% for post in posts %}
        <h2>{{ post.title }}</h2>
    {% endfor %}
{% endblock %}

*Notice how clean the child template is? It contains no <html> or <body> tags!*

9. Best Practices

  • Never Write Complex Logic in Templates: Django's template engine is intentionally restricted. You cannot execute raw Python code (like import os or db.execute()) inside an HTML file. If data needs to be sorted, filtered, or calculated, do it in views.py and pass the *finished* result to the context dictionary.

10. Common Mistakes

  • TemplateDoesNotExist Error: If Django throws this error, it means you placed your home.html in the wrong folder. It MUST be inside blog/templates/blog/. Additionally, ensure you added 'blog' to your INSTALLED_APPS in settings.py, otherwise Django will not even bother searching the blog folder for templates.

11. Exercises

  1. 1. Explain the difference in usage between the {{ }} syntax and the {% %} syntax in Django templates.

12. Coding Challenges

  • Challenge: Create a new View named about, and a new Template named about.html. Use {% extends "blog/base.html" %} to inherit the navbar and footer. Pass a context dictionary from the View containing a key 'company_name' and inject it into an <h1> tag in the template.

13. MCQs with Answers

Question 1

Which Django function is used in views.py to combine an HTTP request, an HTML template, and a context dictionary to return a finished web page?

Question 2

When using Django Template Inheritance, which tag is used in the child template to declare that it is building upon a master skeleton template?

14. Interview Questions

  • Q: Explain the concept of the "Context Dictionary" in a Django View. How does data travel from the database, through the View, and into the final HTML output?
  • Q: Why does Django enforce a restriction against executing complex Python logic directly inside Template files? What architectural principle does this protect?

15. FAQs

Q: Can I pass a database object directly to the template? A: Yes! You can pass entire Django ORM objects. If you pass a User object, you can simply write {{ user.email }} in the HTML, and Django will automatically extract the email attribute.

16. Summary

In Chapter 7, we separated our presentation layer from our logic layer. By utilizing the render() function, we successfully returned dedicated HTML files. We learned how to pass dynamic Python data into these files via Context dictionaries, utilizing Template Tags to render lists dynamically. Finally, we implemented Template Inheritance, solving the problem of duplicate HTML code and paving the way for a scalable frontend architecture.

17. Next Chapter Recommendation

Our data is currently hardcoded into a Python list. Real applications need permanent storage. Proceed to Chapter 8: Working with Models and Databases.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·