search
HomeBackend DevelopmentPython TutorialUnderstanding Django's Architecture: The MTV Pattern.

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

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

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
]

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!")

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'),
]

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
]

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)

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

Inside hello.html, add the following HTML code



    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello Template</title>


    <h1 id="Hello-name">Hello, {{ name }}!</h1>


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

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

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
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
Why are arrays generally more memory-efficient than lists for storing numerical data?Why are arrays generally more memory-efficient than lists for storing numerical data?May 05, 2025 am 12:15 AM

Arraysaregenerallymorememory-efficientthanlistsforstoringnumericaldataduetotheirfixed-sizenatureanddirectmemoryaccess.1)Arraysstoreelementsinacontiguousblock,reducingoverheadfrompointersormetadata.2)Lists,oftenimplementedasdynamicarraysorlinkedstruct

How can you convert a Python list to a Python array?How can you convert a Python list to a Python array?May 05, 2025 am 12:10 AM

ToconvertaPythonlisttoanarray,usethearraymodule:1)Importthearraymodule,2)Createalist,3)Usearray(typecode,list)toconvertit,specifyingthetypecodelike'i'forintegers.Thisconversionoptimizesmemoryusageforhomogeneousdata,enhancingperformanceinnumericalcomp

Can you store different data types in the same Python list? Give an example.Can you store different data types in the same Python list? Give an example.May 05, 2025 am 12:10 AM

Python lists can store different types of data. The example list contains integers, strings, floating point numbers, booleans, nested lists, and dictionaries. List flexibility is valuable in data processing and prototyping, but it needs to be used with caution to ensure the readability and maintainability of the code.

What is the difference between arrays and lists in Python?What is the difference between arrays and lists in Python?May 05, 2025 am 12:06 AM

Pythondoesnothavebuilt-inarrays;usethearraymoduleformemory-efficienthomogeneousdatastorage,whilelistsareversatileformixeddatatypes.Arraysareefficientforlargedatasetsofthesametype,whereaslistsofferflexibilityandareeasiertouseformixedorsmallerdatasets.

What module is commonly used to create arrays in Python?What module is commonly used to create arrays in Python?May 05, 2025 am 12:02 AM

ThemostcommonlyusedmoduleforcreatingarraysinPythonisnumpy.1)Numpyprovidesefficienttoolsforarrayoperations,idealfornumericaldata.2)Arrayscanbecreatedusingnp.array()for1Dand2Dstructures.3)Numpyexcelsinelement-wiseoperationsandcomplexcalculationslikemea

How do you append elements to a Python list?How do you append elements to a Python list?May 04, 2025 am 12:17 AM

ToappendelementstoaPythonlist,usetheappend()methodforsingleelements,extend()formultipleelements,andinsert()forspecificpositions.1)Useappend()foraddingoneelementattheend.2)Useextend()toaddmultipleelementsefficiently.3)Useinsert()toaddanelementataspeci

How do you create a Python list? Give an example.How do you create a Python list? Give an example.May 04, 2025 am 12:16 AM

TocreateaPythonlist,usesquarebrackets[]andseparateitemswithcommas.1)Listsaredynamicandcanholdmixeddatatypes.2)Useappend(),remove(),andslicingformanipulation.3)Listcomprehensionsareefficientforcreatinglists.4)Becautiouswithlistreferences;usecopy()orsl

Discuss real-world use cases where efficient storage and processing of numerical data are critical.Discuss real-world use cases where efficient storage and processing of numerical data are critical.May 04, 2025 am 12:11 AM

In the fields of finance, scientific research, medical care and AI, it is crucial to efficiently store and process numerical data. 1) In finance, using memory mapped files and NumPy libraries can significantly improve data processing speed. 2) In the field of scientific research, HDF5 files are optimized for data storage and retrieval. 3) In medical care, database optimization technologies such as indexing and partitioning improve data query performance. 4) In AI, data sharding and distributed training accelerate model training. System performance and scalability can be significantly improved by choosing the right tools and technologies and weighing trade-offs between storage and processing speeds.

See all articles

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

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.