Home Backend Development Python Tutorial Understanding Django's Architecture: The MTV Pattern.

Understanding Django's Architecture: The MTV Pattern.

Oct 18, 2024 pm 08:16 PM

Understanding Django’s Architecture: The MTV Pattern.

Django follows the MTV (Model-Template-View) pattern for web development. Here's a breakdown of each component:

Model: Defines your data structure and handles interaction with the database, allowing you to store and retrieve data without writing SQL queries manually.

Template: Responsible for rendering HTML and presenting the data to the user. You write HTML mixed with Django Template Language (DTL) to display dynamic content.

View: Acts as the business logic layer. It connects the Model and Template, handles user requests, interacts with the Model, and returns a response (often HTML rendered from the Template).

How Django's Request-Response Cycle Works:

  • A user requests a webpage (via a URL).
  • Django matches the URL to a View.
  • The View fetches data from the Model and passes it to the Template.
  • The Template renders the data into HTML and sends it back as a response to the user.

Step 1: Create a New App in Django.
Once you’ve set up Django (as covered in the previous article), let’s create a new app in your project.

Run these commands:

cd mysite
python3 manage.py startapp core
Copy after login
Copy after login

This creates an app named core inside your mysite project. Your file structure should now look like this:

.
├── core
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   │   └── __init__.py
│   ├── models.py
│   ├── tests.py
│   └── views.py
├── db.sqlite3
├── manage.py
└── mysite
    ├── asgi.py
    ├── __init__.py
    ├── settings.py
    ├── urls.py
    └── wsgi.py
Copy after login
Copy after login

Step 2: Register Your App in the Settings File.
To make Django aware of the new app, you need to add it to the INSTALLED_APPS in mysite/settings.py:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'core',  # add this line
]
Copy after login

Step 3: Create a Basic View.
Let’s create a simple view that returns a “Hello, World!” message.

Open views.py inside the core app and add the following code:

from django.http import HttpResponse

def learn(request):
    return HttpResponse("Hello, World!")
Copy after login

Step 4: Map URLs to the View.
To access this view via a URL, you need to map it in the core/urls.py file. Create this file if it doesn’t exist and add the following:

from django.urls import path
from . import views

urlpatterns = [
    path('learn/', views.learn, name='learn'),
]
Copy after login

Next, include the core app's URLs in the main mysite/urls.py file:

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('core/', include('core.urls')),  # include the core app URLs
]

Copy after login

Now, if you run the server and visit http://127.0.0.1:8000/core/learn/, you should see "Hello, World!" displayed.
Step 5: Create and Render a Template

from django.shortcuts import render

def learn(request):
    context = {'name': 'Django'}
    return render(request, 'hello.html', context)

Copy after login

This view now passes a variable (name) to a template called hello.html.
Step 6: Create a Template Directory and HTML File.
In your core app, create a templates folder and an hello.html file:

mkdir core/templates
touch core/templates/hello.html
Copy after login

Inside hello.html, add the following HTML code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello Template</title>
</head>
<body>
    <h1>Hello, {{ name }}!</h1>
</body>
</html>
Copy after login

When you visit the learn URL again, you should now see "Hello, Django!" in the browser.

Step 7: Create a Basic Model.
Let’s create a simple Post model to store blog posts.

In core/models.py, add the following code:

cd mysite
python3 manage.py startapp core
Copy after login
Copy after login

This Postmodel has two fields: titleand content. The__str__ method ensures that the Post objects are displayed with their titles in the Django admin or shell

Step 8: Apply the Model to the Database.
To create the corresponding table in the database, run these commands:

.
├── core
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   │   └── __init__.py
│   ├── models.py
│   ├── tests.py
│   └── views.py
├── db.sqlite3
├── manage.py
└── mysite
    ├── asgi.py
    ├── __init__.py
    ├── settings.py
    ├── urls.py
    └── wsgi.py
Copy after login
Copy after login

Django will now create a database table for the Post model.

By following these steps, you've successfully created a basic Django app with a model, view, and template. You can now expand upon this foundation by adding more features, such as handling user input, improving the design, and making the app more interactive.

The above is the detailed content of Understanding Django's Architecture: The MTV Pattern.. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1253
29
C# Tutorial
1227
24
Python vs. C  : Applications and Use Cases Compared Python vs. C : Applications and Use Cases Compared Apr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

How Much Python Can You Learn in 2 Hours? How Much Python Can You Learn in 2 Hours? Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

See all articles