Django / Django Basics

Exploring Models, Views, and Templates

In this tutorial, we'll deep dive into Django's MVT (Model, View, Template) architecture. You'll learn how to define your data model, create views to handle the business logic, an…

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Covers the fundamental concepts of Django, including project structure, models, views, and templates.

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!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

CSS Minifier & Formatter

Clean and compress CSS files.

Use tool

Countdown Timer Generator

Create customizable countdown timers for websites.

Use tool

Watermark Generator

Add watermarks to images easily.

Use tool

Date Difference Calculator

Calculate days between two dates.

Use tool

JWT Decoder

Decode and validate JSON Web Tokens (JWT).

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help