Django学习-03 为上文的book app添加数据
1.book文件夹下views的添加books响应函数
from django.shortcuts import render
from django.http.response import JsonResponse
def home(request):
return render(request,"index.html")
def books(request):
books=[
{"id":1, "title":"Python", "price":89.00},
{"id":2, "title":"Flask", "price":89.00},
{"id":3, "title":"Django", "price":89.00},
]
return JsonResponse(books,safe=False)
2.book文件夹下urls添加路由规则
from django.urls import path
from . import views
urlpatterns={
path("",view=views.home,name="home"),
path("api/books", view=views.books, name="book_list")
}
3.进入http://127.0.0.1:8000/book/api/books,即可看见我们添加的json文档
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/ec422ce906a87c662e01b33055ae58b4.png)
4.为了解析json并显示在表中,修改templates文件夹下的index.html文件如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue & Django</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
</head>
<body>
<h1>Vue Django</h1>
<div id="app">
<table>
<tr>
<th>#</th>
<th>标题</th>
<th>定价</th>
</tr>
<tr v-for="book in books">
<td>[[book.id]]</td>
<td>[[book.title]]</td>
<td>[[book.price]]</td>
</tr>
</table>
</div>
<script>
var app = new Vue({
el:"#app",
delimiters:["[[","]]"],
data:{
books:[]
},
mounted:function(){
this.fetchData();
},
methods: {
fetchData(){
axios.get("/book/api/books").then(response=>{
this.books = response.data;
}),err=>{
console.log(err);
};
}
}
})
</script>
</body>
</html>
5.进入http://127.0.0.1:8000/book/,看到结果如下![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/959117ba84060d11fa25663c4be5506a.png)