×
   ❮   
PYTHON FOR DJANGO DJANGO FOR BEGINNERS DJANGO SPECIFICS PAYMENT INTEGRATION API BASICS Roadmap
     ❯   

INTRODUCTION TO DJANGO

Working mechanism

Understanding the Django MVT Workflow

1. URL Dispatcher Calls a View

In Django, when a user makes a request to a specific URL, the URL dispatcher maps that URL to a specific view function. The urls.py file contains patterns that match URLs to views. Django first checks these URL patterns and once a match is found, the corresponding view is called. This is the first step in handling a user’s request.

Example URL Configuration


# urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('articles/', views.article_list, name='article_list'),
]

Here, when a user navigates to /articles/, the article_list view is invoked.

2. View Queries the Database via ORM

Once the view is called, it interacts with the ORM (Object-Relational Mapping) system to retrieve or manipulate data from the database. Django's ORM allows you to query the database using Python classes instead of writing raw SQL queries. This makes database interactions easier and more secure.

Example View Query


# views.py
from .models import Article

def article_list(request):
    articles = Article.objects.all()  # ORM query to fetch all articles
    return render(request, 'articles.html', {'articles': articles})

In this example, the article_list view queries the database through the ORM to retrieve all instances of the Article model and store them in a QuerySet.

3. Database (Models) Interact with ORM

The Models in Django define the structure of your database tables and fields. When the view queries the database, the models interact with the ORM to either send or receive a QuerySet or query, depending on the request. Django's ORM abstracts the underlying database interactions, allowing developers to work with Python objects rather than raw database queries.

Example Model Definition


# models.py
from django.db import models

class Article(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    published_date = models.DateTimeField()

    def __str__(self):
        return self.title

Here, the Article model defines the structure of the Article table in the database. When the view queries for articles, the ORM interacts with this model to fetch the relevant data.

4. View Performs Logical Operations on Data

Once the data is retrieved from the database, the view performs any necessary logical operations or data manipulations before sending it to the template. This could include filtering, sorting, or altering the data to fit the needs of the application.

Example of Data Alteration in View


def article_list(request):
    articles = Article.objects.all().order_by('-published_date')  # Ordering articles by date
    return render(request, 'articles.html', {'articles': articles})

In this example, the articles are ordered by their published_date in descending order before being passed to the template.

5. View Sends Context to the Templating Engine

After any necessary data manipulation, the view passes a context dictionary to the Django templating engine. This dictionary contains the data that will be used to dynamically generate the HTML content. The templating engine takes the context and uses it to render the final HTML page, which is then sent to the user’s browser.

Example of Sending Context to Template


def article_list(request):
    articles = Article.objects.all().order_by('-published_date')
    context = {'articles': articles, 'user': request.user}
    return render(request, 'articles.html', context)

Here, the context dictionary contains both the articles and the current user object, which will be used by the template to dynamically generate content.

6. Templating Engine Generates a Dynamic HTML Page

The Django templating engine uses the context dictionary provided by the view to generate a dynamic HTML page that is customized for the user. The template can access the variables in the context and render them in the HTML structure, and it also applies any permissions or conditions based on the user's access level.

Example Template Usage


<!-- articles.html -->
{% if user.is_authenticated %}
<h1>Welcome, {{ user.username }}!</h1>
<ul>
<li>{% for article in articles %}</li>
<li>{{ article.title }} ({{ article.published_date }})</li>
<li>{% endfor %}</li>
</ul>
{% else %}
<p>Please log in to view the articles.</p>
{% endif %}

In this template, the context data passed from the view is used to generate an article list, and a personalized welcome message is shown if the user is logged in.

7. MVT is a Development Process, Not an Invocation Sequence

It’s important to understand that the Django MVT (Model-View-Template) is a design pattern and development process, not a strict sequence of invocation. While the steps outlined above explain how Django processes a request and generates a response, the MVT structure itself is more of a logical separation of concerns. The Model defines the data structure, the View contains the logic to handle requests and responses, and the Template is responsible for rendering dynamic content. These components work together to handle different aspects of web development but are not tightly coupled in the way they are invoked.

This separation of concerns allows developers to focus on specific parts of the application without worrying about how the other layers are implemented. For example, you can update the templates without affecting the models or views, and vice versa.

Conclusion

In Django’s MVT architecture, the flow begins with a request routed by the URL dispatcher, passes through the view where data is queried and manipulated, and ends with the templating engine rendering a dynamic HTML page. The MVT pattern separates concerns into three logical components—Models, Views, and Templates—making the development process more modular and manageable.

 

Django-tutorial.dev is dedicated to providing beginner-friendly tutorials on Django development. Examples are simplified to enhance readability and ease of learning. Tutorials, references, and examples are continuously reviewed to ensure accuracy, but we cannot guarantee complete correctness of all content. By using Django-tutorial.dev, you agree to have read and accepted our terms of use , cookie policy and privacy policy.

© 2024 Nischal Lamichhane. All Rights Reserved.
Django-tutorial.dev is styled using Bootstrap 5.
And W3.CSS.