models views templates - projectsteward-io/steward-learning GitHub Wiki

How Do Models, Views, and Templates (MVT) Work Together?

Django follows the MVT (Model-View-Template) architecture, which separates concerns to make web development more organized and scalable. This structure consists of:

  • Models: Handle database interactions.
  • Views: Process user requests and retrieve data.
  • Templates: Define the structure and presentation of the data.

1. Models (M) – Data Layer

Models define how data is stored in your database. They are Python classes that Django maps to database tables.

  • Each model represents a table in the database.
  • Fields in a model define the structure of the data.
  • Django's Object-Relational Mapping (ORM) allows interaction with the database without writing raw SQL.

Example Model (models.py)

from django.db import models

class Worker(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField(unique=True)
    department = models.CharField(max_length=50)
    joined_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

Explanation: Worker is a model representing a table in the database. CharField, EmailField, and DateTimeField define different data types. The str method makes objects more readable in the Django admin panel.

2. Views (V) – Business Logic Layer

Views contain the logic that processes requests and returns responses. They act as the bridge between Models and Templates.

When a user requests a page, Django maps the request to a specific view function. Views query the database using models and pass data to templates for rendering.

Example View (views.py)

from django.shortcuts import render
from .models import Worker

def worker_list(request):
    workers = Worker.objects.all()  # Fetch all workers from the database
    return render(request, 'worker_list.html', {'workers': workers})

Explanation:

The worker_list view retrieves all worker data from the database. The view calls render() to send the data to the worker_list.html template.

3. Templates (T) – Presentation Layer

Templates define how data is displayed using Django’s templating engine.

Templates are HTML files with Django template tags ({{ }} and {% %}). They receive data from views and dynamically render it. Example Template (worker_list.html)

<!DOCTYPE html>
<html>
<head>
    <title>Workers List</title>
</head>
<body>
    <h1>Worker Directory</h1>
    <ul>
        {% for worker in workers %}
            <li>{{ worker.name }} - {{ worker.department }}</li>
        {% endfor %}
    </ul>
</body>
</html>

Explanation: {% for worker in workers %} loops through the data passed from the view. {{ worker.name }} dynamically inserts worker names into the HTML. The result is a dynamic web page displaying all workers from the database. How They Work Together (Request-Response Cycle) User Requests a Page β†’ Django URLs route the request to a specific View. View Fetches Data β†’ The view queries the Model for data. View Passes Data to Template β†’ The Template dynamically displays the data. Response is Sent to User β†’ The final HTML page is returned to the browser.

Example Flow: User visits /workers/ worker_list view is triggered View fetches worker data from the database (model) View sends data to the template for rendering User sees the formatted list of workers on their browser

Analogy: MVT as a Restaurant Models = Kitchen & Database β†’ The kitchen (models) stores and prepares the food (data). Views = Waiter (Business Logic) β†’ The waiter (view) retrieves the food from the kitchen and brings it to the table. Templates = Dining Table (Presentation) β†’ The table (template) presents the food to the customer (user) in an appealing way. Key Takeaways Models handle data storage and database interactions. Views process user requests and retrieve data from models. Templates display data in a structured format for users. The MVT pattern separates concerns, making Django apps easier to develop and maintain.

⚠️ **GitHub.com Fallback** ⚠️