Hello! Welcome to your third lesson in the "Introduction to Django" module.
In our last lesson, we laid the physical groundwork for our application. You created a Django project (core) and an app (portfolio), and you now understand the roles of the essential files that Django generates, like settings.py, urls.py, views.py, and models.py.
Today, we're going to explore the architectural blueprint that dictates how these files work together. The learning outcome for this lesson is to explain the MTV (Model-Template-View) pattern in Django. This pattern is the conceptual framework that brings structure and logic to a Django application. Understanding it is crucial because it promotes a clean separation of concerns, which is a cornerstone of building scalable and maintainable software.
1. The Need for an Architectural Pattern
In any web application, there are three fundamental concerns:
- Data: The information the application manages (e.g., user profiles, blog posts, project details).
- Logic: The rules and processes that handle user requests and manipulate data (e.g., retrieving posts, authenticating a user, calculating a result).
- Presentation: The structure and layout of the information sent back to the user (e.g., the HTML page they see in their browser).
You could, in theory, mix all of these into a single, massive Python file. However, as your projects in deep learning have surely taught you, modularity is key. Intertwining data definitions, business logic, and presentation markup results in code that is difficult to read, debug, and extend.
Web frameworks solve this by providing an architectural pattern that enforces a separation of concerns. Django's chosen pattern is called Model-Template-View (MTV).
To begin, let's watch a short video that explains why this separation is so important.
#9 Django tutorials | Model View Template in Django | MVT
This video from the Telusko channel clearly explains the three main components of a web application and why separating them is a fundamental principle of good software design.
Watch from 00:27 to 02:10. Focus on the core idea of separating the three main concerns: the data, the layout, and the business logic.
2. The Components of MTV
Django organizes these three concerns into distinct components: the Model, the Template, and the View. Let's formally define what each one does.
MVT Architecture in Django: Introduction and Comparison ...
The following sections from the article 'MVT Architecture in Django' on Plain English provide clear, concise definitions for each part of the MTV pattern. As you read, mentally map each component to the files we generated in the last lesson.
Please read the sections titled '2.1 Model in Django', '2.2 View in Django', and '2.3 Template in Django'. For each section, focus on its primary responsibility: Model: How it defines the data structure and connects to the database via the ORM. View: Its role as the logical bridge that processes requests. Template: How it handles the final presentation using a special syntax.
To summarize and connect this to our project:
-
Model: This is the data layer. It is the single, definitive source of information about your data. In Django, this is handled by Python classes defined in
models.py. Each class maps to a single database table. This is made possible by Django's Object-Relational Mapper (ORM), an abstraction layer that lets you interact with your database using Python code instead of raw SQL. We will dive deep into the ORM in Module 3. -
View: This is the logic layer. A view is a Python function (or class) in
views.pythat takes a web request and returns a web response. It's responsible for orchestrating everything. It interacts with the Model to fetch data and hands that data off to a Template to render the final output. This is where your application's business logic lives. -
Template: This is the presentation layer. It’s an HTML file with some added Django-specific syntax. The template defines the structure of a page, and the view provides it with the context data to be displayed. The template engine then renders the final HTML, which is sent back to the browser.
3. The MTV Request-Response Cycle
Now that we know the players, let's see how they interact. The entire process begins with a user request and ends with a response. The MTV pattern provides the path that this request follows through your application.
The diagram below illustrates the complete flow.

Let's trace the path of a typical request, referencing the diagram and our project files:
- A user navigates to a URL, say
http://127.0.0.1:8000/portfolio/. The browser sends an HTTP GET request to the Django development server. - The server passes the request into the Django framework.
- Django's URL dispatcher checks the project's root
core/urls.pyfile to find a matching URL pattern. - The
urls.pyfile maps the/portfolio/path to a specific View function inside theportfolio/views.pyfile. - The framework calls the designated view function, passing it an
HttpRequestobject containing information about the request. - The View's logic is executed. It might need data, so it communicates with the Model layer (i.e., classes in
portfolio/models.py). - The Model (via the ORM) queries the database for the required data and returns it to the view as Python objects.
- The View, now holding the data, calls the template engine, specifying which Template to use (e.g.,
portfolio.html) and passing the data to it. - The Template is rendered: the Django template engine combines the template's HTML structure with the data from the view, generating the final HTML content.
- The View encapsulates this HTML in an
HttpResponseobject and returns it. - The framework sends this
HttpResponseback to the user's browser, which then displays the page.
Test your understanding!
Imagine you are building the portfolio app. You need to add a new page that displays the details of a single project (e.g., its title, a longer description, and a link to its GitHub repository).
Which MTV component (Model, View, or Template) and which corresponding file (models.py, views.py, or a new .html file) would be primarily responsible for each of the following tasks?
- Defining the fields that every project must have (e.g.,
title,description,github_link). - Fetching the specific project from the database based on an ID in the URL.
- Arranging the project's title in an
<h1>tag and its description in a<p>tag.
Show answer
- Model (
models.py): The structure of the data, including the fieldstitle,description, andgithub_link, is defined in a model class. - View (
views.py): The business logic for handling the request, parsing the ID from the URL, and querying the database via the model resides in a view function. - Template (a
.htmlfile): The presentation logic, defining how the data is structured in HTML, belongs in a template.
4. Is Django an MVC Framework?
You may have heard of the Model-View-Controller (MVC) pattern, which is very common in web development. Your CSE background might make you wonder how MTV relates to MVC. This is a frequent point of confusion, and clarifying it is important.
- In MVC:
- Model: Manages data and business logic. (Same as Django's Model).
- View: Handles presentation; what the user sees. (Similar to Django's Template).
- Controller: Takes user input, interacts with the Model, and selects a View to render. (Similar to Django's View).
The confusion arises from the naming. In Django, the "View" performs the role of the "Controller" in MVC, and the "Template" performs the role of the "View". The "Controller" part is handled by a combination of the Django framework itself (which processes the request and uses urls.py for routing) and the Django View.
The creators of Django were aware of this and have their own interpretation. A more advanced, and perhaps more accurate, analogy for Django's architecture is the Presentation-Abstraction-Control (PAC) pattern.
The following article explains this distinction clearly.
Beyond MVC - Understanding Django's Architectural Pattern
To prevent future confusion when reading about other frameworks, it's valuable to understand exactly how Django's MTV fits into the broader landscape of architectural patterns like MVC. This article from 'Code n Coffee' provides a concise and insightful analysis.
Read the sections 'Why Django is not MVC', 'Django's PAC-like Architecture', and 'Django's Perspective'. Focus on how the responsibilities of a Django 'View' align with an MVC 'Controller', and why the Django team themselves proposed the MTV terminology.
So, while you might hear Django called an "MVC framework," the more precise term is MTV. The key is to remember the responsibilities: Model for data, Template for presentation, and View for logic.
Conclusion
In this lesson, we moved from the physical file structure to the logical architecture that governs it. You now understand the "why" and "what" of Django's MTV pattern.
Key Takeaways:
- The MTV (Model-Template-View) pattern is an architectural pattern that enforces separation of concerns.
- Model (
models.py): Defines the data structure and interacts with the database via the ORM. - Template (
.htmlfiles): Defines the presentation layer, or what the user sees. - View (
views.py): Acts as the logical hub, receiving requests, processing logic, and coordinating between the Model and Template. - The request-response cycle flows from a URL, to a View, which may use a Model, and then renders a Template to generate the final response.
- Django's MTV is a specific implementation of an MVC-like pattern, where the Django "View" functions as the "Controller" and the "Template" as the "View".
Preview of the Next Lesson:
We've covered a lot of theory. In the next lesson, "Create a simple view function that returns an HTTP response," we will finally write some code. You will implement your very first view in portfolio/views.py, map it to a URL, and see your application return a live response in your browser. This will be the first step in bringing the MTV pattern to life.