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
<!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>
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:
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
def __str__(self):
return self.title
This Post
model has two fields: title
and 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:
python3 manage.py makemigrations
python3 manage.py migrate
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.
Top comments (0)