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

Understanding Django's Architecture: The MTV Pattern.

Mary-Kate Olsen
Release: 2024-10-18 20:16:30
Original
825 people have browsed it

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!

source:dev.to
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template