1. MVT Intro
MVC Introduction
Django follows the MTV (Model-Template-View) pattern, which is similar to MVC (Model-View-Controller) but with different terminology.
MVC (Traditional) | MTV (Django) | Description |
---|---|---|
Model | Model | Handles data and database queries. |
View | Template | Manages the presentation layer (HTML, CSS). |
Controller | View (in Django) | Processes user requests and interacts with models. |
Where is the Controller in Django?
In Django, the Controller role is handled by the View (views.py).
1. Example: Django View as Controller
Consider a basic Django view that acts as a controller:
1️⃣ Define the Model (models.py
)
from django.db import models
class Book(models.Model): title = models.CharField(max_length=255) author = models.CharField(max_length=100) published_date = models.DateField()
def __str__(self): return self.title
2️⃣ Create the Controller (View) in views.py
from django.shortcuts import renderfrom .models import Book
def book_list(request): books = Book.objects.all() # Fetching data from the model return render(request, 'book_list.html', {'books': books}) # Sending data to the template
Here, book_list()
acts as the Controller:
- Handles the request (
request
object). - Fetches data from the Model (
Book.objects.all()
). - Passes data to the Template (
book_list.html
).
3️⃣ Add URL Mapping (urls.py
)
from django.urls import pathfrom .views import book_list
urlpatterns = [ path('books/', book_list, name='book_list'),]
- URL Dispatcher (urls.py) acts as a router, directing requests to the appropriate Controller (view).
4️⃣ Create the Template (templates/book_list.html
)
<!DOCTYPE html><html><head> <title>Book List</title></head><body> <h1>Available Books</h1> <ul> {% for book in books %} <li>{{ book.title }} by {{ book.author }} ({{ book.published_date }})</li> {% endfor %} </ul></body></html>
- The Template only handles the presentation logic.