Exploring Models, Views, and Templates

Tutorial 4 of 5

Introduction

Welcome to this tutorial where we will explore Django's MVT (Model, View, Template) architecture. Our primary focus will be on defining your data model, creating views to manage the business logic, and designing templates to control the presentation of your data.

You will learn:

  1. The basics of Django's MVT architecture.
  2. How to create and utilize models.
  3. How to create views and templates.
  4. How to link all these components together in a Django project.

Prerequisites:
- Basic knowledge of Python
- Basic understanding of Django framework

Step-by-Step Guide

Django MVT Architecture

Django MVT (Model-View-Template) is a software design pattern. It's a collection of three important components Model View and Template. The Model helps to handle the database. It's a data access layer which handles the data. The View is used to execute the business logic and interact with a model to carry data and renders a template. The Template is a presentation layer which handles User Interface part completely.

Models

A model is a representation of your data structure. It’s a Python object that is mapped to a database table. Django gives you a high-level, Pythonic interface to your database tables, taking care of the SQL for you.

from django.db import models

class Blog(models.Model):
    title = models.CharField(max_length=200)
    description = models.TextField()

    def __str__(self):
        return self.title

In this example, we have created a Blog model with a title field (limited to 200 characters) and a description field (a text field with no character limit).

Views

Views handle the business logic of your application. They receive HTTP requests from the user, interact with the model to get the requested data, and then render the appropriate template with this data to generate an HTTP response.

from django.shortcuts import render
from .models import Blog

def blog_list(request):
    blogs = Blog.objects.all()
    return render(request, 'blog/blog_list.html', {'blogs': blogs})

In this example, we have a view blog_list that fetches all the Blog objects from the database and passes them to the blog_list.html template.

Templates

Templates are the presentation layer in the MVT pattern. They define how the data should be presented to the user.

{% extends 'base.html' %}

{% block content %}
  <h2>Blog List</h2>
  {% for blog in blogs %}
    <h3>{{ blog.title }}</h3>
    <p>{{ blog.description }}</p>
  {% endfor %}
{% endblock %}

This template extends a base template (base.html) and replaces its content block with a list of blogs.

Code Examples

Let's create a simple blog application as an example.

Models

# models.py
from django.db import models

class Blog(models.Model):
    title = models.CharField(max_length=200)
    description = models.TextField()

    def __str__(self):
        return self.title

Here, we have a Blog model with title and description fields.

Views

# views.py
from django.shortcuts import render
from .models import Blog

def blog_list(request):
    blogs = Blog.objects.all()  # Fetch all blog objects
    return render(request, 'blog/blog_list.html', {'blogs': blogs})  # Pass them to the template

In our view, we fetch all the Blog objects and pass them to the blog_list.html template.

Templates

<!-- blog_list.html -->
{% extends 'base.html' %}

{% block content %}
  <h2>Blog List</h2>
  {% for blog in blogs %}
    <h3>{{ blog.title }}</h3>
    <p>{{ blog.description }}</p>
  {% endfor %}
{% endblock %}

The template receives the blogs context variable from the view and displays each blog's title and description.

Summary

In this tutorial, we covered the basics of Django's MVT architecture. We learned about models, views, and templates, and how they interact with each other. We also created a simple blog application as an example.

Next, try to extend our blog application. Maybe add a feature to create new blogs, or add a detail view where users can read one blog at a time.

Practice Exercises

  1. Create a new model Author with fields name and bio. Modify the Blog model to include a foreign key to Author.
  2. Create a new view and template to display all blogs by a specific author.
  3. Add a feature to create new authors.

Solutions, explanations, and tips for these exercises will be provided in the next tutorial. Keep practicing and happy coding!