This content originally appeared on DEV Community and was authored by Lisa Mosweta
What is MVC?
MVC stands for:
- Model – Handles data and business logic.
- View – Displays data to the user.
- Controller – Accepts user input, processes it, and interacts with the model.
This architecture helps separate concerns, meaning each component handles its own responsibility keeping our code clean and organized.
Django’s Twist:
Django is “sort of” MVC, but with a unique flavor. It uses the MTV architecture, which maps like this:
Django MTV Traditional MVC Purpose
Model Model Handles the data, database, and business logic
Template View Displays the data to the user (HTML, CSS)
View Controller Handles the logic and connects everything
Yup, Django’s “View” is actually the Controller in the traditional sense, and the “Template” is the actual View.
Why Does This Matter?
Understanding this mapping clears up confusion when navigating Django projects. Here’s what each component looks like in action:
Model (models.py
): Defines your database structure.
View (views.py
): Contains the logic to fetch data and choose what template to render.
Template (.html files
): Renders the UI using context passed from the view.
Building a Basic Django App Example
Here’s a quick overview of how these parts fit together in a blog app:
models.py
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
views.py
def post_list(request):
posts = Post.objects.all()
return render(request, 'blog/post_list.html', {'posts': posts})
<!-- post_list.html -->
<h2>{{ post.title }}</h2>
<p>{{ post.content }}</p>
Final Thoughts
While Django uses different naming conventions, it follows the same principles of MVC. Learning to embrace the MTV structure is key to mastering Django and building clean, efficient apps.
This content originally appeared on DEV Community and was authored by Lisa Mosweta