1
0

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 5 years have passed since last update.

JavaユーザーのDjangoチュートリアル

Posted at

Web開発はSpringBootしかしたことないエンジニアです。試行錯誤しながら、DjangoでHelloWorldしていきます

condaをインストールしてたらいろいろ楽だよ

condaは、主にPython用に作られたパッケージ管理システムと環境マネジメントシステムです。 単体ではリリースされておらず、Anaconda、Anacondaサーバー、Minicondaに内包されているものです。機械学習ライブラリのパッケージ等を簡単にインストールできます
Gradleみたいなもんかなーって感じの認識です。

セットアップ

djangoインストールしたよ

$ django-admin startproject hello

でdjangoアプリのひな形ができます

hello
  ├ manage.py
  └ hello
      ├─ __init__.py
      ├─ settings.py
      ├─ urls.py
      └─ wsgi.py

できました

$ python manage.py startapp world

で"world"という名前のアプリが追加できます(JavaでいうところのController?)

hello
  ├─ manage.py
  ├─ hello
  │    ├─ __init__.py
  │    ├─ settings.py
  │    ├─ urls.py
  │    └─ wsgi.py
  └─ world
       ├─ __init__.py
       ├─ admin.py
       ├─ apps.py
       ├─ models.py
       ├─ tests.py
       ├─ urls.py
       └─ wsgi.py

コーディング

ひな形ができましたので次にコードをいじってHelloWorldしていきます。
最初にsettings.pyを編集してworldアプリケーションを組み込みます。
INSTALLED_APPSタグにworldを入れます。

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'world'
]

次に「HelloWorld!」を出力するメソッドをつくります。
world\vies.pyを編集します。

from django.http.response import HttpResponse

# Create your views here.
def helloworld(request):
    return HttpResponse('Hello World!')

つづいてプロジェクトのディスパッチャを設定していきます。ディスパッチャには二つの種類があります。

  • プロジェクトディスパッチャ
  • アプリケーションディスパッチャ

プロジェクトディスパッチャはプロジェクトに来たリクエストをどのアプリケーションで実行するか振り分けるディスパッチャ
アプリケーションディスパッチャはアプリケーションに来たリクエストに対してレスポンスをどのViewで実行するかを振り分けるディスパッチャ

プロジェクトのディスパッチャから行います。
最新のDjangoではurlディパッチャの記法がかわってるから注意
hello\urls.pyを編集します。

from django.contrib import admin
from django.conf.urls import include,url

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

続いて、アプリケーションディスパッチャを行います。
world直下にurls.pyを作成します。

from django.conf.urls import url
from . import views

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

パラメータ指定なしのときにviesのhelloworldメソッドを返すという設定ができました。
・・・
プロジェクトディスパッチャでまとめてしたらよくない?って思いますよね。
できないこともないのですがSpringでいうところの

  • RequestMapping(プロジェクトディスパッチャ)
  • GetMapping(アプリケーションディスパッチャ)
    みたいな感じでディレクト構造やコード自体を見やすくするためだと思いましょう。

実行

ここまできたら、サーバーを起動してみましょう

$ python manage.py runserver 0.0.0.0:8000

localhost:8080につなぐと。。。

HelloWorld!

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?