0
0
Djangoframework~5 mins

MTV pattern mental model in Django

Choose your learning style9 modes available
Introduction

The MTV pattern helps organize a web app into clear parts: data, logic, and display. It keeps code neat and easy to manage.

Building a website that shows data from a database
Creating a web app where users can add or change information
Separating how data is handled from how it looks on the page
Working on a team where different people handle data, logic, and design
Making it easier to update the website without breaking other parts
Syntax
Django
Model: Defines data structure and database tables
Template: Defines how data is shown to users (HTML)
View: Handles logic, gets data from Model, sends it to Template

The Model is like a blueprint for your data.

The View is the middleman that connects data and display.

Examples
This Model defines a Book with a title.
Django
class Book(models.Model):
    title = models.CharField(max_length=100)

# Model defines data structure
This Template loops over books and shows each title.
Django
{% for book in books %}
  <p>{{ book.title }}</p>
{% endfor %}

# Template shows book titles in HTML
This View gets all Book data and sends it to the Template named 'books.html'.
Django
def book_list(request):
    books = Book.objects.all()
    return render(request, 'books.html', {'books': books})

# View gets all books and sends to Template
Sample Program

This simple Django app shows a list of book titles. The Model defines the data, the View gets all books, and the Template displays them.

Django
from django.shortcuts import render
from django.db import models

# Model
class Book(models.Model):
    title = models.CharField(max_length=100)

# View
def book_list(request):
    books = Book.objects.all()
    return render(request, 'books.html', {'books': books})

# Template (books.html):
# {% for book in books %}
#   <p>{{ book.title }}</p>
# {% endfor %}
OutputSuccess
Important Notes

MTV is similar to MVC but uses different names to fit Django's style.

Templates should only handle display, not data logic.

Views connect Models and Templates, keeping code organized.

Summary

MTV splits a web app into Model (data), Template (display), and View (logic).

This pattern helps keep code clean and easy to update.

Each part has a clear job, making teamwork easier.