The Model-View-Template (MVT) architecture is a core design pattern in Django. It is similar to the Model-View-Controller (MVC) pattern used in other frameworks but adapted to Django’s design philosophy. Here’s an overview of its components:
1. Model
Represents the data layer of the application.
It defines the structure and behavior of the data (e.g., database tables) through Python classes.
Django’s Object-Relational Mapping (ORM) allows seamless interaction with the database using Python code.
Example responsibilities:
- Define database schema.
- Perform data validations.
- Implement business logic related to the data.
Example:
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=100)
price = models.DecimalField(max_digits=10, decimal_places=2)
description = models.TextField()
2. View
Represents the business logic and controls how data is presented to the user.
It handles HTTP requests, processes data (via Models), and passes the appropriate data to the Template.
Views can return:
- HTML responses (rendered with a Template).
- JSON responses (e.g., for APIs).
- Other HTTP responses (e.g., redirects, errors).
Example:
from django.shortcuts import render
from .models import Product
def product_list(request):
products = Product.objects.all()
return render(request, 'product_list.html', {'products': products})
3. Template
Represents the presentation layer.
It is responsible for defining how the data sent by the View is displayed to the user.
Uses Django’s templating language, which supports:
- Variable rendering.
- Control structures (loops, conditionals).
- Template inheritance for reusability.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Product List</title>
</head>
<body>
<h1>Products</h1>
<ul>
{% for product in products %}
<li>{{ product.name }} - ${{ product.price }}</li>
{% endfor %}
</ul>
</body>
</html>
Django architecture – Interview Questions
Q 1: What architecture does Django follow?
Q 2: What is the role of Model in Django?
Q 3: What is a View in Django?
Q 4: What is a Template in Django?
Q 5: How is MVT different from MVC?
Django architecture – Objective Questions (MCQs)
Q1. Django follows which architecture pattern?
Q2. In Django MVT, the ‘V’ stands for:
Q3. Which component of MVT handles the database layer?
Q4. Which part of the Django architecture handles HTML files?
Q5. In Django, the controller part is handled by: