Django’s framework architecture follows a variation of the traditional MVC (Model-View-Controller) pattern, but it is known as MTV (Model-Template-View) in Django’s terminology. The separation of concerns in Django ensures that different components (data, logic, and presentation) are handled in a structured and organized manner.
Django’s MTV architecture:
1. Model:
Product
model in an e-commerce app that defines fields like name
, price
, and description
.from django.db import models
class Product(models.Model):
name = models.CharField(max_length=255)
price = models.DecimalField(max_digits=10, decimal_places=2)
description = models.TextField()
2. Template:
html
<h1>Product List</h1>
<ul>
{% for product in products %}
<li>{{ product.name }} - ${{ product.price }}</li>
{% endfor %}
</ul>
3. View:
python
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})
4. URL Routing (Controller in MVC):
/products/
URL to the product_list
view.python
from django.urls import path
from . import views
urlpatterns = [
path('products/', views.product_list, name='product_list'),
]
Workflow of MTV Architecture:
Request Handling:
urls.py
) receives the request and maps the URL to the appropriate View.Business Logic in View:
Data Rendering with Template:
Response:
Diagram of Django’s MTV Architecture:
text
User Request --> URL Routing --> View --> Model (Database)
| |
View <-- Template (Render HTML)
|
HTTP Response (HTML)
Benefits of Django’s MTV Architecture:
Separation of Concerns: The separation between models, views, and templates makes the code more modular, reusable, and easier to maintain.
Scalability: Each component can be scaled or modified independently (e.g., changing the database schema without affecting the view logic).
Reusability: Models and templates can be reused in different parts of the application, reducing code duplication.
Django’s MTV architecture simplifies web development by keeping data handling, business logic, and presentation separate yet efficiently interconnected.