LoginSignup
10
20

More than 5 years have passed since last update.

DjangoでWebアプリケーションを作る

Last updated at Posted at 2017-04-13

Qiita初投稿です。
以前インターンシップでDjangoを使ったWebアプリケーション開発をしていましたが、 一から作ったことはなかったのでサーバー起動までやってみました。

前提

  • Python 3.5.1
  • pyenv
  • pyenv-virtualenv
  • Django 1.11
  • macOS & Homebrew
  • MySQL

環境構築

開発環境を構築します。

terminal
$ brew install pyenv pyenv-virtualenv mysql
$ pyenv install 3.5.1
$ pyenv global 3.5.1
$ pyenv virtualenv 3.5.1 django-sample-3.5.1

$ mysql.server start

Djangoアプリケーションの作成

ディレクトリ構成は以下のようにしました。
調べたらプロジェクト名/プロジェクト名のフォルダを作り、その下にローカルアプリを追加していく構成が多かったです。

django-sample
.
├── README.md
├── manage.py
├── libs
│   └── # pip installでライブラリが入る
├── requirements.txt
├── templates
│   ├── common
│   │   └── _base.html
│   └── home
│       └── index.html
└── django-sample
    ├── settings.py
    ├── urls.py
    └── views.py

自動生成してくれるコマンドがあるようですが、今回は手動で行いました。

terminal
$ mkdir django-sample
$ cd django-sample
$ pyenv local django-sample-3.5.1

必要なライブラリをrequirements.txtに書きます。

requirements.txt
django==1.11
django-extensions==1.7.8
mysqlclient==1.3.10

普通にインストールしてもいいのですが、Railsのvendor/bundle みたいにプロジェクト下に置きたかったので ./libs以下にインストールします。

terminal
$ pip install -r requirements.txt -t libs

manage.pyを編集します。

manage.py
import os
import sys

# ./libsのパスを通す
sys.path.append(os.path.join(os.path.dirname(__file__), 'libs'))

settings_module_name = os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django-sample.settings')

if __name__ == '__main__':
    from django.core.management import execute_from_command_line
    execute_from_command_line(sys.argv)

settings.pyを編集します。データベースのユーザ名、パスワード等は環境変数に設定しました。
データベースやユーザ等の作成は省略します。
ログイン機能等試していたので今回必要でない設定が含まれているかもしれません。

django-sample/settings.py
import os


ROOT_PATH = os.path.dirname(os.path.dirname(__file__))

DEBUG = os.getenv('DJANGO_SAMPLE_BEBUG')

ALLOWED_HOSTS = [
    'localhost'
]

INSTALLED_APPS = [
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.messages',
    'django.contrib.sessions',
    'django.contrib.staticfiles',
    'django.contrib.sites',
    'django_extensions'
]

MIDDLEWARE_CLASSES = [
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware'
]

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'HOST': os.getenv('DJANGO_SAMPLE_DATABASE_HOST'),
        'NAME': os.getenv('DJANGO_SAMPLE_DATABASE_NAME'),
        'USER': os.getenv('DJANGO_SAMPLE_DATABASE_USER'),
        'PASSWORD': os.getenv('DJANGO_SAMPLE_DATABASE_PASSWORD')
    }
}

SESSION_COOKIE_NAME = 'djangosample'
SECRET_KEY = os.getenv('DJANGO_SAMPLE_SECRET_KEY')
CSRF_HEADER_NAME = 'HTTP_X_CSRFTOKEN'
CSRF_SESSION_NAME = 'csrf'
CSRF_COOKIE_SECURE = True
MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage'

ROOT_URLCONF = 'django-sample.urls'

LOGIN_REDIRECT_URL = '/'

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(ROOT_PATH, 'static')
]

SITE_ID = 1

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(ROOT_PATH, 'templates')
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'django.template.context_processors.media',
                'django.template.context_processors.i18n',
                'django.template.context_processors.request',
                'django.template.context_processors.static'
            ]
        }
    }
]

データベースのマイグレーションをします。

terminal
$ python manage.py migate

Viewクラスを定義します。

django-sample/views.py
from django.views.generic import TemplateView


class HomeView(TemplateView):
    template_name = 'home/index.html'

    def get_context_data(self, **kwargs):
        context = super(HomeView, self).get_context_data(**kwargs)
        return context

home_view = HomeView.as_view()

ブラウザで表示されるテンプレートを編集します。

templates/home/index.html
{% extends 'common/_base.html' %}

{% block content %}
  <h1>Hello World!!</h1>
{% endblock %}
templates/common/_base.html
<!DOCTYPE html>
<html>
<head>
  <title>django-sample</title>
</head>
<body>
{% block content %}
{% endblock %}
</body>
</html>

最後にルーティングを設定します。

django-sample/urls.py
from django.conf import settings
from django.conf.urls import include, url

from . import views


urlpatterns = [
  # /
  url(r'^$', views.home_view)
]

サーバーを立ち上げて http://localhost:8000 にアクセスします。

terminal
$ python manage.py runserver

最後に

今回のコードはGithubにも上げています。
https://github.com/yukidallas/django-sample

次回はログイン機能(メール登録、Twitterログイン)の実装について投稿予定です。

10
20
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
10
20