Django Webページの作成手順

Django Webページの作成手順

pythonのWebアプリケーションフレームワーク「Django」でアプリケーションを作成して、URLの構成設定までの手順です。

環境

  • OS  CentOS Linux release 8.0.1905 (Core)
  • Python 3.6.8
  • pip 9.0.3
  • django 3.0

プロジェクト作成

helloという名前でプロジェクトを作成してます。

django-admin startproject hello

## プロジェクトに移動
cd hello

アプリケーション作成

testappと名前でアプリケーションを作成します。

python manage.py startapp testapp

testapp配下にurls.pyというファイルを作成し下記の内容で編集します。

from django.urls import path
from . import views
 
urlpatterns = [
    path('', views.index, name='index'),
    path('hello/', views.hello, name='hello'),    
]

同様にviews.pyというファイルを作成し下記の内容で編集します。

from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
 
def index(request):
    return HttpResponse("<h1>Top page</h1>") 
 
def hello(request):
    return HttpResponse("<h1>Hello World</h1>")

helloプロジェクトディレクトリ構成

tree -l

<出力結果>
.
├── db.sqlite3
├── hello
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-36.pyc
│   │   ├── settings.cpython-36.pyc
│   │   ├── urls.cpython-36.pyc
│   │   └── wsgi.cpython-36.pyc
│   ├── asgi.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── manage.py
└── testapp
    ├── __init__.py
    ├── __pycache__
    │   ├── __init__.cpython-36.pyc
    │   ├── admin.cpython-36.pyc
    │   ├── models.cpython-36.pyc
    │   ├── urls.cpython-36.pyc
    │   └── views.cpython-36.pyc
    ├── admin.py
    ├── apps.py
    ├── migrations
    │   ├── __init__.py
    │   └── __pycache__
    │       └── __init__.cpython-36.pyc
    ├── models.py
    ├── tests.py
    ├── urls.py
    └── views.py

helloディレクトリ配下にあるurls.pyを下記のとおりに編集します。

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('testapp.urls')),
]

起動します。

python manage.py runserver

ブラウザから http://localhost:8000 にアクセスすると「TOPページ」と表示され

http://localhost:8000/helloにアクセスすると「Hello World」と表示されます。