The MVT Pattern
Django organizes code into Models, Views and Templates — the MVT pattern.
Django follows the MVT pattern: Model, View, Template. It is Django's take on the classic MVC idea.
- Model — defines your data and talks to the database.
- View — a Python function or class that receives a request and returns a response. It holds your logic.
- Template — an HTML file with placeholders that renders the final page.
A request flows through the URLconf first, which decides which view runs. The view can read data through a model and hand it to a template, which produces the HTML response.
Example
# URLconf picks the view -> view builds context -> template renders it
from django.shortcuts import render
from .models import Post
def post_list(request):
posts = Post.objects.all() # Model
return render(request, "posts.html", {"posts": posts}) # TemplateWhen to use it
- A blog application separates its Post model, list/detail views, and HTML templates using the MVT pattern.
- An online store keeps product database logic in models, pricing calculations in views, and product cards in templates.
- A school portal uses MVT so designers modify HTML templates independently without touching Python business logic.
More examples
Model defines data structure
The Model layer declares the Article table structure Django will create in the database.
from django.db import models
class Article(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
published = models.DateTimeField(auto_now_add=True)View fetches and passes data
The View retrieves articles from the Model and passes them to a Template via context.
from django.shortcuts import render
from .models import Article
def article_list(request):
articles = Article.objects.order_by("-published")
return render(request, "articles/list.html", {"articles": articles})Template renders the data
The Template loops over articles passed by the view and renders each with Django template tags.
{% for article in articles %}
<article>
<h2>{{ article.title }}</h2>
<p>{{ article.body|truncatewords:30 }}</p>
</article>
{% endfor %}
Discussion