この記事は 約 1分12秒 で読めます。
前回からの続きやっていきます。
前回までの準備でAPIが整いましたので、テンプレートにvue.jsを組み込んでいきたいと思います。
このログは、こちらのレポジトリでDjango+Dockerセットアップ後の環境を想定しています。
URL設定
プロジェクトのurls.pyにarticleまでの経路を設定します。
1 2 3 |
urlpatterns = [ url(r'', include('article.urls')), # 追加 ] |
そのあとは、アプリケーション側でもurlを設定します。
1 2 3 4 5 6 7 |
from django.conf.urls import url from .views import IndexTemplateView app_name = 'article' urlpatterns = [ url(r'^article/$', IndexTemplateView.as_view(), name="index"), ] |
ビュー作成
経路を設定できたので、ビューを作っていきましょう。
1 2 3 4 |
from django.views.generic import TemplateView class IndexTemplateView(TemplateView): template_name = 'article/index.html' |
テンプレート作成
ビューができたので、表示用のテンプレートを作っていきましょう。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 |
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>Vue-js | Django | Crud App</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="A simple crud app made with the vue js and django"> <meta name="keywords" content="vuejs, django, crudapp, restapi"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> </head> <body> <style type="text/css"> [v-cloak] { visibility:hidden; } .loading { text-align: center; } h1 { width: 100%; } .div01 { display: block; width: 100%; padding-bottom: 20px; } </style> <div id="starting"> <div class="container"> <div class="row"> <h1>vue.jsでCRUD、DjangoでAPI <br /> <button class="btn btn-success" data-toggle="modal" data-target="#addArticleModal">ADD ARTICLE</button> </h1> <table class="table" v-cloak> <thead> <tr> <th scope="col">#</th> <th scope="col">Heading</th> <th scope="col">Action</th> </tr> </thead> <tbody> <tr v-for="article in articles"> <th scope="row">${article.article_id}</th> <td>${article.article_heading}</td> <td> <button class="btn btn-info" v-on:click="getArticle(article.article_id)">Edit</button> <button class="btn btn-danger" v-on:click="deleteArticle(article.article_id)">Delete</button> </td> </tr> </tbody> </table> <!-- Add Article Modal --> <div class="modal fade" id="addArticleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">ADD ARTICLE</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <form v-on:submit.prevent="addArticle()"> <div class="modal-body"> <div class="form-group"> <label for="article_heading">Article Heading</label> <input type="text" class="form-control" id="article_heading" placeholder="Enter Article Heading" v-model="newArticle.article_heading" required="required" > </div> <div class="form-group"> <label for="article_body">Article Body</label> <textarea class="form-control" id="article_body" placeholder="Enter Article Body" v-model="newArticle.article_body" required="required" rows="3"></textarea> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Save changes</button> </div> </form> </div> </div> <div class="loading" v-if="loading===true">Loading...</div> </div> <!-- End of article modal --> <!-- Edit Article Modal --> <div class="modal fade" id="editArticleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">EDIT ARTICLE</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <form v-on:submit.prevent="updateArticle()"> <div class="modal-body"> <div class="form-group"> <label for="article_heading">Article Heading</label> <input type="text" class="form-control" id="article_heading" placeholder="Enter Article Heading" v-model="currentArticle.article_heading" required="required" > </div> <div class="form-group"> <label for="article_body">Article Body</label> <textarea class="form-control" id="article_body" placeholder="Enter Article Body" v-model="currentArticle.article_body" required="required" rows="3"></textarea> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary m-progress" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Save changes</button> </div> </form> </div> </div> <div class="loading" v-if="loading===true">Loading...</div> </div> <!-- End of edit article modal --> </div> </div> <div class="loading" v-if="loading===true">Loading...</div> </div> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/vue@2.5.13/dist/vue.js"></script> <script src="https://cdn.jsdelivr.net/npm/vue-resource@1.3.5"></script> <script type="text/javascript"> function readCookie (name) { 'use strict'; var nameEQ = name + '='; var ca = document.cookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) === ' ') { c = c.substring(1, c.length); } if (c.indexOf(nameEQ) === 0) { return c.substring(nameEQ.length, c.length); } } return null; } // Djangoはこれが必要みたい var csrftoken = readCookie('csrftoken'); var apiUrl = '/api/1.0/articles/'; var app = new Vue({ 'el': '#starting', // デリミタ変更 'delimiters': [ '${', '}' ], 'data': { 'articles': [{}], 'loading': false, 'currentArticle': {}, 'message': null, 'newArticle': { 'article_heading': null, 'article_body': null } }, 'mounted': function () { 'use strict'; this.getArticles(); }, 'methods': { 'getArticles': function () { 'use strict'; this.loading = true; this.$http.get(apiUrl) .then((response) => { this.articles = response.data.results; this.loading = false; }) .catch((err) => { this.loading = false; console.log(err); }); }, 'getArticle': function (id) { 'use strict'; this.loading = true; this.$http.get(apiUrl + id + '/') .then((response) => { this.currentArticle = response.data; $('#editArticleModal').modal('show'); this.loading = false; }) .catch((err) => { this.loading = false; console.log(err); }); }, 'addArticle': function () { 'use strict'; this.loading = true; this.$http.post( apiUrl, this.newArticle, {'headers': {'X-CSRFToken': csrftoken}} ) .then(() => { this.loading = false; this.getArticles(); this.newArticle.article_heading = null; this.newArticle.article_body = null; $('body').removeClass('modal-open'); $('.modal-backdrop').remove(); $('#addArticleModal').modal('hide'); }) .catch((err) => { this.loading = false; console.log(err); }); }, 'updateArticle': function () { 'use strict'; this.loading = true; this.$http.put( apiUrl + this.currentArticle.article_id + '/', this.currentArticle, {'headers': {'X-CSRFToken': csrftoken}} ) .then((response) => { this.loading = false; this.currentArticle = response.data; this.getArticles(); }) .catch((err) => { this.loading = false; console.log(err); }); }, 'deleteArticle': function (id) { 'use strict'; this.loading = true; this.$http.delete( apiUrl + id + '/', {'headers': {'X-CSRFToken': csrftoken}} ) .then(() => { this.loading = false; this.getArticles(); }) .catch((err) => { this.loading = false; console.log(err); }); } } }); </script> </body> </html> |
ページを開いて動きの確認
http://localhost:8000/article/を開くと
以下のような画面になっていると思います。
記事の追加と編集と削除が行えるCRUDの基本が完成しましたね!
HTMLのソースを見れば何をしているのかだいたい理解できると思います。
vue.jsもわかりやすいですね。
以上です。