1、项目结构
![](https://img2018.cnblogs.com/blog/1220447/202002/1220447-20200211164536076-577029185.png)
2、models
init.py
from .BookModel import Book
BookModel
from django.db import models
class Book(models.Model):
b_name = models.CharField(max_length=32)
b_price = models.FloatField(default=1)
def to_dict(self):
return {'id': self.id, 'b_name': self.b_name, 'b_price': self.b_price}
3、views
init.py
from .BookAPI import book, books
BookAPI.py
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from Api.models import Book
@csrf_exempt
def books(request):
if request.method == "GET":
book_list = Book.objects.all()
book_list_json = []
for book in book_list:
book_list_json.append(book.to_dict())
data = {
'status': 200,
'msg': 'ok',
'data': book_list_json
}
return JsonResponse(data=data)
elif request.method == "POST":
b_name = request.POST.get('b_name')
b_price = request.POST.get('b_price')
book = Book()
book.b_name = b_name
book.b_price = b_price
book.save()
data = {
'status': 201,
'msg': 'add success',
'data': book.to_dict()
}
return JsonResponse(data=data, status=201)
@csrf_exempt
def book(request, bookid):
if request.method == "GET":
book_obj = Book.objects.get(pk=bookid)
data = {
'msg': 'ok',
'status': 200,
'data': book_obj.to_dict()
}
return JsonResponse(data=data)
elif request.method == "DELETE":
book_obj = Book.objects.get(pk=bookid)
book_obj.delete()
data = {
'msg': 'delete success',
'status': 204,
# 'data': {}
}
return JsonResponse(data=data, status=204)
4、urls.py
from django.conf.urls import url
from Api import views
urlpatterns = [
url(r'^books/$', views.books, name='books'),
url(r'^books/(?P<bookid>\d+)/', views.book, name='book'),
]
5、static->>CreateBook.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>BookCreate</title>
<script type="text/javascript" src="/static/js/jquery.js"></script>
<script type="text/javascript">
$(function () {
$("button").click(function () {
var b_name = $("#b_name").val();
var b_price = $("#b_price").val();
$.post('/api/books/', {'b_name': b_name, 'b_price': b_price}, function (data) {
console.log(data);
if (data['status'] === 201){
window.open('/static/html/BookList.html', target="_self");
}
} )
})
})
</script>
</head>
<body>
<div id="container">
<form action="#">
<span>BookName:</span> <input type="text" id="b_name" placeholder="please input your book name">
<br>
<span>BookPrice:</span> <input type="text" id="b_price" placeholder="please input your book price" >
</form>
<button>Create</button>
</div>
</body>
</html>
6、static->>BookList.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>BookList</title>
<script type="text/javascript" src="/static/js/jquery.js"></script>
<script type="text/javascript">
/**
$(function () {
$.getJSON("/api/books/", function (data) {
console.log(data);
})
})
*/
$(function () {
// $("button").click(function () {
$.getJSON("/api/books/", function (data) {
console.log(data);
if (data['status'] === 200){
var $ul = $("ul");
var books = data['data'];
for(var i=0; i < books.length; i++){
var $li = $("<li></li>");
$li.html(books[i]['b_name']);
$li.appendTo($ul);
}
}
})
// })
})
</script>
</head>
<body>
<div id="container">
<button>ClickToLoad</button>
<ul>
</ul>
</div>
</body>
</html>