2017年11月30日木曜日

Django appを作成

1)Projectを作成、cloud9環境ではすでに作成されたので、不要
django-admin startproject mysite

2)appを作成
python manage.py startapp polls

Projects vs. apps
What’s the difference between a project and an app? An app is a Web application that does something – e.g., a Weblog system, a database of public records or a simple poll app. A project is a collection of configuration and apps for a particular website. A project can contain multiple apps. An app can be in multiple projects.

3)Viewを作成
polls/views.py を編集

from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")

4)To call the view, we need to map it to a URL
 polls/urls.py を作成

from django.conf.urls import url

from . import views

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

5)To point the root URLconf at the polls.urls module

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

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

6)DBの設定
MySQLのアクセスモジュールを追加
sudo pip3 install PyMySQL

Projectフォルダーにsettings.pyのDATABASESを変更
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'c9',  #dbname
        'USER': 'XXXXc9',       #username
        'PASSWORD': 'password',
        'HOST': '',
        'PORT': '',
    }
}

manage.pyに以下を追加
import pymysql
pymysql.install_as_MySQLdb()

7)migrate実施
python manage.py migrate
settings.pyのINSTALLED_APPSに必要なTableが作成されれば、DB設定OK


0 件のコメント:

コメントを投稿