3.B] Explain MTV Development Pattern.
Answer:
The MTV (Model-Template-View) development pattern is the architecture used by Django to build web applications. It is similar to the MVC (Model-View-Controller) pattern but with some differences in terminology and structure. Here’s an overview of each component in the MTV pattern:
1. Model
- Definition: The Model is the layer that handles the data and business logic of the application. It defines the structure of the data, including the fields and their types, and includes methods for interacting with the database.
- Responsibilities:
- Database Schema: Defines the schema of the database tables.
- Data Access: Provides methods for querying and manipulating data.
- Validation: Includes business logic for validating data.
- Example:
# models.py from django.db import models class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=100) publication_date = models.DateField() def __str__(self): return self.title
2. Template
- Definition: The Template is the presentation layer that handles the presentation and rendering of data. It is responsible for generating the HTML that is sent to the user’s browser.
- Responsibilities:
- HTML Generation: Defines how data is displayed to the user.
- Dynamic Content: Uses template tags and filters to insert dynamic data into the HTML.
- Separation of Concerns: Keeps the presentation logic separate from the business logic.
- Example:
<!-- templates/book_list.html --> <!DOCTYPE html> <html> <head> <title>Book List</title> </head> <body> <h1>Book List</h1> <ul> {% for book in books %} <li>{{ book.title }} by {{ book.author }}</li> {% endfor %} </ul> </body> </html>
3. View
- Definition: The View is the layer that handles the request and response logic. It receives requests from the user, interacts with the Model to retrieve or modify data, and then selects the appropriate Template to render the response.
- Responsibilities:
- Request Handling: Processes incoming requests and interacts with the Model to fetch or update data.
- Response Generation: Chooses the appropriate Template to render and sends the response back to the user.
- Business Logic: Includes application-specific logic that determines what data to present and how.
- Example:
# views.py from django.shortcuts import render from .models import Book def book_list(request): books = Book.objects.all() return render(request, 'book_list.html', {'books': books})
Summary
- Model: Defines the data structure and provides methods for interacting with the database.
- Template: Handles the presentation of data, generating the HTML for display in the browser.
- View: Manages the logic for processing requests and selecting the appropriate Template for the response.