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 1 year has passed since last update.

Djangoを新規案件で取り扱うことになったので概要をまとめてみます。①

Posted at

まず従来のWebページを開く際のイメージ図
image.png

クライアント側が特定のファイルに対して
「このページが欲しい」とリクエストを送って
それに対してサーバー側から欲しかったファイルが送られる。(レスポンス)

きわめてシンプルですね。

一方Djangoというと、、
image.png
ざっとこんな感じらしい。

Djangoのスタート

$ python -m django --version

でバージョンの確認ができる。インストールされている前提

image.png

$ django-admin startproject mysite

すると、mysideディレクトリは以下に下記のような構造が作られる。
image.png

その後、先ほど作られたmysiteディレクトリに移動したら
下記コマンドを実行する

python manage.py runserver

すると、コンソール部分に下記のような出力が、、、
image.png

Flaskの「flask --app app --debug run」の実行時と似ていますね
表示されているURL「http://127.0.0.1:8000/」にアクセスしてみると
image.png
Djangoスタートアップページが表示される。

ここまで来て気付いた点

manege.pyを実行したらサーバーと接続した。
Flaskでいうmain.pyみたい。

app=run()

があるファイル。

上記図でいうと、url.pyはFlaskのapp.pyにあたりそうかな。
コードを見ると、ルーティングの設定をしていそう。

ルーティングは分かったけど、肝心なtemplateは?
どうやって画面を表示しているんだ?HTMLとか?

とりあえず疑問を残したまま次に進んでみる

image.png

What’s?
そういえばまだviews.pyとか作られていなかった。

image.png

とりあえず言われたように実行してみます。

$ python manage.py startapp polls

image.png
pollのフォルダが作られました

image.png

とりあえずviews.pyに言われたように記載します。

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")

更に、pollフォルダ配下にurls.pyを作らないといけないらしい。
1階層手前の物は何なんだ?

from django.urls import path

from . import views

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

image.png
!?
image.png

なにか言っています!

image.png

runserverして/pollsにアクセスしたらIndexの物が表示されました!

ここまでのまとめ

urls.py
はURLを定義している?
URLを生成した上でviewsのメソッドと紐づけている。HttpResponse。
Flaskのレンダーテンプレートみたいなもの。

今のところのイメージでは、
例えばFlaskにおいて、
●app.py
BluePrintでモジュール毎にroute関数を分けている。
●vies/test.py
BluePrintで飛ばされた場所。
実際の処理やルーティング処理が記載されている。
メインの記述場所?
●main.py
app=run()
を実行することで、app.pyを呼んでいる?

という感じで作られていて、FlaskとDjangoとを照らし合わせてみると

●urls.py
→app.py

●views.py
→Viewsフォルダ内
 ルーティング処理部分

●manage.py
→main.py
呼びだす大元。

まだ出てきていないm「template」と「model.py」に関しては、
恐らくルーティング時にtemplateを参照するのでしょう。
templateにはFlaskのtemplatesと同様HTML・CSS等記述して、ページ情報を書き込んでいるのでしょう。

modelに関してはDBにアクセスする際にインスタンス化してORM的にDBと接続・操作するのでしょう。

とりあえずここまでわかれば、後はDjangoの書き方になれるだけかな。

Nextage

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?