Lesson 2: The Model-View-Template (MVT) Pattern – Like MVC, But With More Magic and Less Headaches
Hello again, coding wizard! 🧙♂️ If you’ve made it this far, congratulations—you’re officially past Lesson 1 (and hopefully didn’t throw your keyboard out the window). Now, it’s time to dive into Django’s secret weapon: the Model-View-Template (MVT) pattern. It’s like MVC, but with fewer headaches and more magic.
In today’s magical journey, we’re also going to create your very first model for blog posts. By the end of this lesson, you’ll be bending data to your will like a true sorcerer. 🪄
Step 1: Activate the Virtual Environment (a.k.a. Enter the Wizard’s Lair)
Before casting any spells (a.k.a. running Django commands), we need to enter our virtual lair—our virtual environment. If you haven’t activated it yet, open your terminal, navigate to your project directory, and run this command:
source venv/bin/activate
You’ll know you’re inside your magical bubble when your terminal starts showing (venv)
at the beginning of every line. Think of it as your personal coding Hogwarts—except with more Python and fewer owls.
Step 2: Create the Blog App (Every Wizard Needs a Workshop)
Now that you’ve entered your magical workspace, it’s time to set up the blog app. Think of it as your wizard’s workshop, where all your blogging spells will come to life. Run this command to create the app:
python3 manage.py startapp blog
Django will work its magic and create a blog
directory where all the ingredients for your blog—models, views, templates—will live. It’s like getting a shiny new spellbook, but less likely to catch fire.
The project structure will look something like this:
myblog/
blog/
migrations/
__init__.py
admin.py
apps.py
models.py # <-- This is where we'll define the BlogPost model
views.py
...
myblog/
__init__.py
settings.py
urls.py
wsgi.py
manage.py
Step 3: Register the App in settings.py
(Make it Official)
Now that your blog app exists, we need to tell Django about it. Open your project’s settings.py
file and add 'blog'
to the INSTALLED_APPS
list:
INSTALLED_APPS = [
# Other installed apps...
'blog',
]
Now your blog app is officially part of the Django club. It’s like adding your name to the Hogwarts registry—but with fewer detentions.
Step 4: Create the BlogPost
Model (Time to Create Some Magic)
Here comes the fun part! It’s time to create the BlogPost model, which will represent all the blog posts you’ll be crafting. In Django, models are like the magical blueprints for your data—think of them as enchanted scrolls for your database.
Open the models.py
file inside the blog
directory and add the following code:
from django.db import models
class BlogPost(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
What’s Going on Here?
title
: A text field where the blog post title will live. Maximum length is 200 characters (because we all know that overly long titles are just showing off).content
: The body of your post. This is where the magic happens (or where your stream of consciousness goes wild).created_at
: A timestamp that records when the post was created. You won’t need to worry about this—Django will handle it for you like an invisible elf.__str__
: This method ensures Django shows something useful when it references a post. Here, it’ll show the title, because “Untitled Post #42” isn’t quite as charming.
Step 5: Create and Apply Migrations (Tell the Database What’s Up)
Now that we’ve defined our BlogPost
model, we need to make the database aware of it. This is where migrations come in. Migrations are like sending magical scrolls to the database, telling it what to do.
- First, run the following command to create the migration file:
python3 manage.py makemigrations
Django will respond with something along the lines of: “Migrations for ‘blog’: 0001_initial.py”—which is Django-speak for “Alright, I know what you want me to do.”
- Next, apply the migration to the database:
python3 manage.py migrate
And voilà! Your database now has a shiny new table for storing blog posts. If you listen closely, you can almost hear it whisper, “I’m ready for your words of wisdom (or cat photos).”
Step 6: Use Django Admin to Manage Posts (Time to Play with the Big Boys)
One of Django’s coolest features is the admin panel. It’s basically a control room where you can manage your blog posts like a wizard with an army of enchanted scrolls.
But first, we need to register the BlogPost
model in the admin panel. Open admin.py
in the blog
directory and add this code:
from django.contrib import admin
from .models import BlogPost
admin.site.register(BlogPost)
Now, fire up the server:
python3 manage.py runserver
Go to http://127.0.0.1:8000/admin/ and check out the magic for yourself. If you haven’t created a superuser yet (the all-powerful admin account), do it now:
python3 manage.py createsuperuser
Django will prompt you to enter a username, email, and password. Don’t worry—you don’t have to use a magical password, just make sure it’s something secure (like “notapassword123”).
Once you’ve logged in, you’ll see your BlogPost
model ready to be managed. You can now add, edit, and delete blog posts with just a few clicks—no wands required.
Step 7: Display the Posts in the Front-End (Because What’s the Point of Magic If No One Sees It?)
Great! We’ve created the posts and managed them in the admin panel. Now, let’s actually display them on your site—because what good is a blog if it’s not showing off your words to the world (or at least to your mom)?
- Add a View: Open
views.py
in theblog
directory and create a view that retrieves all the blog posts from the database and sends them to a template:
from django.shortcuts import render
from .models import BlogPost
def blog_index(request):
posts = BlogPost.objects.all().order_by('-created_at')
return render(request, 'blog_index.html', {'posts': posts})
- Create a Template: Inside the
blog
directory, create a folder namedtemplates
(if it doesn’t already exist). Then, create a file calledblog_index.html
:
<!DOCTYPE html>
<html>
<head>
<title>My Blog</title>
</head>
<body>
<h1>Welcome to My Blog!</h1>
<ul>
{% for post in posts %}
<li><strong>{{ post.title }}</strong> - {{ post.created_at }}</li>
<p>{{ post.content }}</p>
{% endfor %}
</ul>
</body>
</html>
This template will loop through all the blog posts and display the title, date, and content for each one. When you visit the blog URL, your posts will finally be visible to the world (or, you know, to anyone willing to read them).
Step 8: Setting Up urls.py
(The Magical Pathway)
Now, let’s connect our new blog view to the Django project. You need to create a URL route so that when someone visits a specific address (like /blog
), Django knows to show the list of blog posts. This is where urls.py
comes into play.
- Create
urls.py
for the Blog App: Inside theblog
directory, create a new file calledurls.py
and add the following code:
from django.urls import path
from . import views
urlpatterns = [
path('', views.blog_index, name='blog_index'),
]
- Include Blog URLs in the Main
urls.py
: To make sure Django recognizes the blog URLs, we need to include them in the mainurls.py
file located in themyblog
directory. Open theurls.py
file and modify it as follows:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('blog/', include('blog.urls')), # Add this line to include the blog URLs
]
This tells Django to include all the URLs from the blog
app when someone visits the /blog/
URL.
Conclusion of Lesson 2
Look at you go! 🎉 You’ve created your first Django app, defined a model for blog posts, set up URL routing, and displayed the posts on the front-end. By now, you’re basically a Django wizard. 🧙♂️
Next time, we’ll level up by adding forms—because what’s a blog without letting people (or bots) send you random messages and comments? Until then, take a moment to admire your work (and maybe reward yourself with some chocolate frogs). You’ve earned it!
See also
- Lesson 6 – Event Delegation: Mastering Efficiency in Interaction
- Lesson 5 – Event Magic: Making Web Pages Interactive
- Lesson 4 – DOM Manipulation: Turning the Web into Your Personal Playground
- Lesson 6: User Profiles – Because Everyone Deserves a Little Spotlight
- Lesson 2 – Loops and Conditionals: Making Decisions and Repeating Yourself (Without Going Crazy)