6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Django で Hello World

Last updated at Posted at 2018-03-31

Django のサイト
django

Arch Linux で django のインストール

sudo pacman -S python-django

確認したバージョン

$ python --version
Python 3.11.3

$ python -m django --version
4.2.3

プロジェクトの作成

プロジェクト proj01
アプリケーション home
を作成します。

django-admin startproject proj01
cd proj01/
python manage.py migrate
python manage.py startapp home

この時点で開発サーバーを動かしてみます。

python manage.py runserver

ブラウザーで http://127.0.0.1:8000/
 にアクセスすると、Django のディフォールトのページが表示されます。
image.png

更に設定をすすめます。

メッセージを表示するプログラムの編集
次のプログラムに差し替えます。

home/views.py
from django.http import HttpResponse

def index(request):
    str_out = "<p>Good Afternoon</p>"
    str_out += "<p>こんにちは</p>"
    return HttpResponse(str_out)

proj01/settings.py の編集
'home' を加えます。

proj01/settings.py
INSTALLED_APPS = [
    'home',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

proj01/urls.py の編集

proj01/urls.py
from django.contrib import admin
from django.urls import include
from django.urls import path

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

home/urls.py の作成

from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
]

再び開発サーバーを動かします。

python manage.py runserver

ブラウザーで http://127.0.0.1:8000/
 にアクセスすると

django_mar3102.png

静的なファイルを表示するようにするには、
home の下に static というフォルダーを作ります。

mkdir home/static
mkdir home/static/images

home/static/images に画像ファイル(linux_logo.jpg)を入れて、それを表示してみます。

qiita_apr0401.png

Gunicorn でサーバーを動かす

gunicorn proj01.wsgi

外部からアクセスできるようにする

設定

proj01/settings.py
省略
ALLOWED_HOSTS = ['*']
省略

サーバー起動

python manage.py runserver 0.0.0.0:8000

gunicorn

gunicorn proj01.wsgi -b 0.0.0.0
6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?