MVT Architecture

Django follows the MVT (Model-View-Template) architecture pattern. It separates an application into different components, making the code easier to manage, maintain, and scale.

Components of MVT

1. Model

A Model represents the data structure of your application and interacts with the database.

Responsibilities:

  • Define database tables
  • Store and retrieve data
  • Perform database operations

Example:

from django.db import models

class Student(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField()

In this example, Django creates a database table named Student with name and email fields.

2. View

A View contains the business logic. It receives requests from users, processes data, interacts with models, and returns a response.

Example:

from django.http import HttpResponse

def home(request):
    return HttpResponse("Welcome to Django")

When a user visits the URL linked to this view, Django executes the function and returns a response.

3. Template

A Template is responsible for displaying data to users. Templates are usually HTML files containing dynamic content.

Example (home.html):

<h1>Welcome {{ name }}</h1>

The {{ name }} variable is replaced with actual data before the page is rendered.

Request Flow in Django

User Request
      ↓
     URL
      ↓
     View
      ↓
    Model
      ↓
  Database
      ↓
    Model
      ↓
     View
      ↓
   Template
      ↓
User Response

Example Flow

  1. User visits /students/
  2. URL routes requests to a view.
  3. View fetches student data from the model.
  4. The model interacts with the database.
  5. View sends data to a template.
  6. Template renders HTML.
  7. The user receives the final web page.

MVT vs MVC

MVCDjango MVT
ModelModel
ViewTemplate
ControllerView

Django handles much of the controller functionality internally, which is why it uses MVT instead of MVC.

Key Takeaway

  • Model → Manages data and database operations.
  • View → Handles business logic and requests.
  • Template → Displays data to users.

Together, these three components form Django’s MVT architecture and help keep applications organized and maintainable.