Django Views and Templates
# CHAPTER 7
Django Views and Templates
1. Introduction
WhileHttpResponse("<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
extendsandblock.
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 yourblog 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
Createblog/templates/blog/home.html:
Now, update blog/views.py to use render instead of HttpResponse:
*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:
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 Pythonforloop orifstatement.
In home.html:
*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
Rewrite the Child: blog/templates/blog/home.html
*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 osordb.execute()) inside an HTML file. If data needs to be sorted, filtered, or calculated, do it inviews.pyand pass the *finished* result to the context dictionary.
10. Common Mistakes
-
TemplateDoesNotExist Error: If Django throws this error, it means you placed your
home.htmlin the wrong folder. It MUST be insideblog/templates/blog/. Additionally, ensure you added'blog'to yourINSTALLED_APPSinsettings.py, otherwise Django will not even bother searching theblogfolder for templates.
11. Exercises
-
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 namedabout.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
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?
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 aUser 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 therender() 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.