0
1

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

はじめてのDjangoルーティング

Posted at

やりたいこと

  • Djangoを初めて触る。
  • Djangoのルーティングを試したい。
  • CakePHPなどMVCフレームワークのルーティングは実装経験がある。
  • class-based view と function-based view の使い分けなどは後日。

前提

設定ファイル urls.py

URLとクラス・ファンクションの対応付けを設定するファイル。
CakePHPの routes.php に相当するもの。

vi /home/yamato/myapp/myapp/urls.py

urlと、それに対応するクラス、ファンクションを下記のように記載する。

from django.contrib import admin
from django.urls import path
import myapp.views as hello
urlpatterns = [
    path('admin/', admin.site.urls),
    path('hoge/', hello.index),
]

hoge がurlで、hello.index がクラス・ファンクション。

ビューファイル views.py

views.py は、myapp作成時点ではデフォルトでは存在していないので、
まずはファイルを新規作成する。
urls.py と views.py を同じディレクトリに置く。

vi /home/yamato/myapp/myapp/views.py

下記のようにファンクションを実装する。

from django.http import HttpResponse
def index(request):
    return HttpResponse("I am Kenichiro-Yamato.")

解説

ブラウザから
http://192.168.1.xx:8000/hoge/
にアクセスした際、下記のように表示させたいとする。

image.png

これは、下記の2ステップで実装できる。

(1) views.py を作成する。

vi /home/yamato/myapp/myapp/views.py
from django.http import HttpResponse
def index(request):
    return HttpResponse("I am Kenichiro-Yamato.")
  • function名が index である点に着目。
  • ファイル位置が /home/yamato/myapp/myapp である点に着目。

(2) urls.py に追記する。

vi /home/yamato/myapp/myapp/urls.py
from django.contrib import admin
from django.urls import path
import myapp.views as hello
urlpatterns = [
    path('admin/', admin.site.urls),
    path('hoge/', hello.index),
]
  • import myapp.views as hello に着目。
  • path('hoge/', hello.index), に着目。

修正してみる。

views.py を下記のように修正。

from django.http import HttpResponse
def printMessageFromYamato(request):
    return HttpResponse("I am Kenichiro-Yamato.")
  • ファンクション名を index から printMessageFromYamato に変更した。

urls.py を下記のように修正。

from django.contrib import admin
from django.urls import path
import myapp.views as view
urlpatterns = [
    path('admin/', admin.site.urls),
    path('yamato/', view.printMessageFromYamato),
]
  • import myapp.views as view に修正した。
  • path('yamato/', view.printMessageFromYamato) に修正した。

にアクセスして下記が表示されたらOK。

image.png

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?