LoginSignup
6
6

More than 1 year has passed since last update.

djangoでウェブアプリを作る(初心者)

Posted at

#1 djangoでウェブアプリを作る

このページの目的

djangoを使って、開発サーバーでhtmlを表示できるようになる
(理解より結果を優先するので、細かい説明は省く)

目次

○プロジェクトとアプリとは

・プロジェクトとアプリの作成

○htmlを表示させる

○プロジェクトとアプリとは

まずdjangoにおいて、プロジェクトは1つで、アプリは1個~複数個(1つは必須)作ることができる。

・アプリはプロジェクト内の1つの機能のようなもの

・シンプルなプロジェクトならアプリは1つでOK

・プロジェクト(ここでは下の階層のdjango_websiteフォルダ)は全体設定(settings.py、urls.py) 以外はほとんど使わない

・プロジェクトとアプリを作る

django_websiteという名前のプロジェクトを作る

ターミナル
django-admin startproject django_website

django_websiteに移動して、websiteという名前のアプリを作る

ターミナル
cd django_website
python manage.py startapp website

websiteあぷり(フォルダ)を登録する

settings.py
#django_website/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'website'
]

カッコ内に記述したURLからのアクセスを許可

settings.py
#django_website/settings.py
ALLOWED_HOSTS = ["*"] #「*」は全てという意味

○htmlを表示させる

まず、websiteアプリにtemplatesフォルダ作成、この中にindex.htmlを作成

index.html
#website/templates/index.html
<h1>Hello World</h1>

次にURLを受け取ってから、htmlを表示させるための設定をしていく

index.htmlをユーザーに返すビューを追加

views.py
#website/views.py
from django.views.generic import TemplateView
class IndexView(TemplateView):
    template_name = "index.html"

website/urls.pyを作成

ビューとURLを結びつける

urls.py
#website/urls.py
from django.urls import path
from .views import IndexView #同じ階層のview.pyからIndexViewを読み込む
urlpatterns = [
    path('', IndexView.as_view()),
]

URLを送られたときに見に行くファイルの指定

urls.py
#django_website/urls.py
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include("website.urls")) #websiteフォルダのurls.pyを読み込む
]

最後に開発サーバを立ち上げるとindex.htmlが表示される

(ctrl + C で停止)

ターミナル
python manage.py runserver

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