Djangoroidの奮闘記

python,django,angularJS1~三十路過ぎたプログラマーの奮闘記

Angular4 + Django1.11 vol.1

参考サイト

https://www.codingforentrepreneurs.com/projects/angular-django/

Getting Started Angular4+Django

  • djangular4というフォルダを作成する。さらに、djangular4/client, djangular4/backend というサイトをそれぞれ作成する。

  • clientフォルダに、joincfe/github のtry-angular-v4をgit cloneしてくる。

$ git clone https://github.com/codingforentrepreneurs/Try-Angular-v4.git .
// ここのピリオドがポイント

$ npm install
// package.jsonに記載があるmoduleをinstallする。

$ ng serve
// angularのコードをtranscompileして、localserverを起動する。

$ rm -rf .git
// gitのrepositoryを削除する
  • djangoの環境を作成する。
$ pyenv virtualenv djangular4 // 仮想環境を作成する
$ pip install django djangorestframework // django djangorestframework をpip installする

A Django URL Catch-all

  • django startprojectで、新しいprojectを開始する。$ django-admin.py startproject tryangular .

  • settings.pyにstaticfileの設定を追記する。

STATIC_URL = '/static/'

STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static-root')

STATICFILES_DIRS = [
        os.path.join(BASE_DIR, 'static')
]
  • urls.pyにangularで表示するurlをcatchするための設定をする。
from django.conf.urls import url
from django.contrib import admin
from django.views.generic.base import TemplateView #template viewをimportする

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^.*', TemplateView.as_view(template_name="ang_home.html"), name='home'), #
]
  • templatesフォルダを作成して、その中にang_home.htmlを作成する。
<h1>Hello Django!</h1>
  • またsettings.pyにtemplatesのフォルダの場所を指定する。
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
  • http://127.0.0.1:8000/でも、http://127.0.0.1:8000/dddでも、表示されるページが、ang_home.htmlになっていればOK。

  • 今後は、個別に表示したいurlがある場合は、(adminのように)、r'^.*'より上に書く。

まとめ

  • これで一通りの準備は完了ぽい。
  • .(ピリオド)を使うのがポイントだったな。