Bài 1 Tạo ứng dụng web hello world Django

Written by admin
Posted on Tue, 06/08/2021 - 08:22
58 views

Share Everywhere

Table of contents

Cấu trúc simple project:

(venv) % tree
.
├── ce
│   ├── __init__.py
│   ├── admin.py
│   ├── apps.py
│   ├── migrations
│   │   └── __init__.py
│   ├── models.py
│   ├── tests.py
│   └── views.py
├── manage.py
└── simple
    ├── __init__.py
    ├── __pycache__
    │   ├── __init__.cpython-36.pyc
    │   └── settings.cpython-36.pyc
    ├── settings.py
    ├── urls.py
    └── wsgi.py

4 directories, 14 files

Sau khi tạo xong, mình tạo một view print "Hello World!" trên web:

# simple/settings.py
# Application definition
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'ce'
]

# simple/urls.py
from django.conf.urls import url, include
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^', include('ce.urls'))
]

# ce/urls.py
# Create new file `ce/urls.py` to define url of app ce
from django.conf.urls import url
from ce import views

urlpatterns = [
    url(r'^$', views.index),
]

# ce/views.py
# Define view
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello World!")

Run server!

(venv) % python manage.py runserver 

Performing system checks...

System check identified no issues (0 silenced).

May 03, 2018 - 02:22:31

Django version 1.9, using settings 'simple.settings'

Starting development server at http://127.0.0.1:8000/

Quit the server with CONTROL-C.