Djangoroidの奮闘記

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

Angular4 + Django1.11 vol.2

参考サイト

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

ng build to Django Static

  • $ ng build --prod で、production versionのbuildを実行する。(結果、bundle.jsが作成される)

  • buildしたファイルの出力先をdjangoのstaciファイル内にする。

$ ng build --prod --output-path /Users/yassy/Desktop/djangular4/backend/src/static/ang --watch --output-hashing none

// --output-path で出力先を指定
// --watchで、変更があったら自動でbuildするモードに切り替えられる
// --output-hashing none で、build時に作成されるhashをなくすことができる。
  • deploy.sh ファイルを作成する。deployのときに実行するコマンドを記載する。
ng build --prod --output-path /Users/yassy/Desktop/djangular4/backend/src/static/ang --watch --output-hashing none

Django render Angular

  • static/ang/index.htmlをang_home.htmlにコピペする。さらに、load staticで、django templateで、staticfileを読み込むようにする。
{% load static %}
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Srvup</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
      <!-- index.html -->
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<link href="{% static 'ang/styles.bundle.css' %}" rel="stylesheet"/></head>
<body>
  <app-root>Loading...</app-root>
  <script type="text/javascript" src="{% static 'ang/inline.bundle.js' %}"></script>
  <script type="text/javascript" src="{% static 'ang/polyfills.bundle.js' %}"></script>
  <script type="text/javascript" src="{% static 'ang/vendor.bundle.js' %}"></script>
  <script type="text/javascript" src="{% static 'ang/main.bundle.js' %}"></script>
</body>
</html>
  • 無事表示された!しかし、image ファイルなどが読み込まれていない。。。ang/assets/videos.jsonの中のpathがdjangoと一致してないのが原因ぽい。なので、そのimage のpathを修正する。
    {
     "name": "Welcome",
     "slug": "item-1",
     "embed": "1hyjLD7pk10",
     "image": "/static/ang/assets/images/nature/4.jpg",
     "featured": true
    }
    ...
  • 次に、vides.service.ts内のendpoint(videos.jsonにアクセスするpath)も修正する。
const endpoint = '/static/ang/assets/json/videos.json'
  • http://127.0.0.1:8000/にアクセスしてみる。。。error!というか画像が表示されない。。。原因は、videos.jsonをbuildあとのファイル(angフォルダ以下のファイル)を修正していたため、buildが実行されるたびに、上書きされていたためだった(^^; なので、client/assets/json/videos.jsonの方のpathを修正して再度buildする。

  • 無事表示された(^^)

  • home.component.tsの、defaultImageのpathも修正する。

videoListDefaultImage = '/static/ang/assets/images/videos/1.jpg'

まとめ

  • angularアプリと、djangoアプリは別物と考える。
  • angularアプリ作成→build→deployという流れだが、django backendに使うときは、angularアプリ作成→build output→outputしたファイルを、djangoに静的ファイルとして扱わせる という流れになるのか。
  • build –watch にしておくことで、常にtranscompile + outputされる。そのため、基本的に、django側にoutputされたファイルを修正ではなく、angularアプリの方のファイルを修正する(djangoは、angularアプリからoutputされるファイルを扱うという役割)