๐ Welcome to Day 5 of Django Journey!
Today, we break down the architecture that powers Django apps โ the MVT pattern โ and compare it to the classic MVC. If you've heard about Models, Views, Templates, and got confused, you're not alone! Letโs untangle that web. ๐ธ๏ธ
๐ง MVC vs MVT โ Whatโs the Difference?
Before diving into Django specifics, letโs explore what these patterns mean.
๐งฉ MVC (Model-View-Controller)
This pattern separates your application into:
- Model โ The data and database layer.
- View โ The UI or frontend display.
- Controller โ The logic that controls data flow between the Model and View.
Used in frameworks like Laravel, Ruby on Rails, and ASP.NET.
๐งฉ MVT (Model-View-Template) in Django
Django follows MVT, which looks very similar:
- Model โ Represents data (just like MVC).
- View โ Handles logic and pulls data from the model.
- Template โ The HTML interface shown to users.
But here's the twist:
In Django, the View is like the Controller in MVC, and the Template acts as the View.
๐ Learn more: Django vs MVC on Real Python
๐๏ธ Letโs Understand Each MVT Component
๐น 1. Model โ Your Data's Structure
The Model defines how data is stored in the database using Djangoโs ORM (Object Relational Mapping). It avoids writing raw SQL.
Example:
class BlogPost(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
`
- Models map directly to database tables.
- Each class = 1 table, each field = 1 column.
๐ Django Models Guide
๐น 2. View โ The Brain ๐ง
The View is the middleman. It receives user requests, talks to the model, then selects the template to display.
Example:
python
def home(request):
posts = BlogPost.objects.all()
return render(request, 'home.html', {'posts': posts})
- Think of Views as your appโs logic and decision maker.
- It returns a response, usually HTML.
๐น 3. Template โ The Frontend
Templates are what users see โ HTML files with dynamic placeholders.
Example:
html
{% for post in posts %}
<h2>{{ post.title }}</h2>
<p>{{ post.content|truncatewords:20 }}</p>
{% endfor %}
- Templates use Django Template Language (DTL).
- They display data passed by the view.
๐ Django Templates
๐น Bonus: URL Routing
Django uses a URL dispatcher to connect browser paths to views.
Example:
python
path('', views.home, name='home')
๐ Django URL Patterns
๐งญ The Flow of Data (Visual Recap)
plaintext
Browser Request
โ
URLConf (urls.py)
โ
View (views.py)
โ
Model (if needed)
โ
Template (HTML page)
โ
Browser Response
๐ Admin Panel โ MVT in Action
Register a model and get a full-featured admin UI to create, read, update, and delete records!
python
admin.site.register(BlogPost)
Then visit 127.0.0.1:8000/admin
after running:
bash
python manage.py createsuperuser
๐ Django Admin Docs
Top comments (0)