1.restful请求方式
一个视图对应多个操作(增删改查)
老的方式
views.py
from django.shortcuts import render
from django.http import HttpResponse,request,QueryDict, JsonResponse
from myapp.models import User
from django.views.generic import View
# Create your views here.
def user(request):
if request.method == "GET":
return HttpResponse("获取用户")
elif request.method == "POST":
name = request.POST.get('name')
city = request.POST.get('city')
sex = request.POST.get('sex')
age = request.POST.get('age')
User.objects.create(
name=name,
city=city,
sex=sex,
age=age
)
return HttpResponse("创建用户成功!")
elif request.method == "PUT":
data = QueryDict(request.body)
id = data.get('id')
user_obj = User.objects.get(id=id)
user_obj.city = data.get('city')
user_obj.sex = data.get('sex')
user_obj.age = data.get('age')
user_obj.save()
# 方式2
# data = {'city': data.get('city'), 'sex': data.get('sex'), 'age': data.get('age')}
# User.objects.filter(id=id).update(**data)
res = {'code': 200, 'msg': '更新成功!'}
return JsonResponse(res)
elif request.method == "DELETE":
# request有GET和POST,没有DELETE和PUT
data = QueryDict(request.body)
id = data.get('id')
try:
User.objects.get(id=id).delete()
res = {'code': 200, 'msg': '删除用户成功!'}
except Exception:
res = {'code': 500, 'msg': '删除用户失败!'}
return JsonResponse(res)#返回的是json对象,httpresponse返回的是字符串
def user_edit(request):
id = request.GET.get('id')
user_obj = User.objects.get(id=id)
return render(request, 'user_edit.html', {'id': id, 'user': user_obj})
def user_add(request):
return render(request, 'user_add.html')
def user_list(request):
user_list = User.objects.all()
return render(request,'user_list.html',{'user_list': user_list})
# 上面是老式的api请求方式,
user_list.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>列出所有用户</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
</head>
<body>
<button><a href="/myapp/user_add" target="_blank">创建用户</a></button>
<table border="1">
<thead>
<tr>
<th style="display: none">ID</th>
<th>姓名</th>
<th>城市</th>
<th>性别</th>
<th>年龄</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for i in user_list %}
<tr>
<td style="display: none">{{ i.id }}</td>
<td>{{ i.name }}</td>
<td>{{ i.city }}</td>
<td>{{ i.sex }}</td>
<td>{{ i.age }}</td>
<td>
<button><a href="/myapp/user_edit?id={{ i.id }}" target="_blank">编辑</a></button>
<button id="del" onclick="delUser(this)">删除</button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<script>
function delUser(obj) {
confirm = confirm('是否删除该用户?');
if (confirm) {
id = $(obj).parent().parent().find("td:eq(0)").text(); // 获取button父元素td,再获取td父元素tr,最后获取tr第一个td值
data = {'id': id};
console.log(id)
$.ajax({
type: 'DELETE',
url: '/myapp/user/',
data: data,
success: function (result) {
if(result.code === 200) {
alert(result.msg);
#
location.reload();
} else {
alert(result.msg)
}
}
})
}
}
</script>
</body>
</html>
user_edit.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>编辑用户</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
</head>
<body>
<h2>编辑用户</h2>
<form action="#">
<input type="text" name="id" value="{{ user.id }}" style="display: none">
姓名:<input type="text" name="name" value="{{ user.name }}"><br>
城市:<input type="text" name="city" value="{{ user.city }}"><br>
性别:<input type="text" name="sex" value="{{ user.sex }}"><br>
年龄:<input type="text" name="age" value="{{ user.age }}"><br>
<input type="button" value="提交" onclick="go()">
</form>
<script>
function go() {
var id = $('input[name=id]').val();
var name = $('input[name=name]').val();
var city = $('input[name=city]').val();
var sex = $('input[name=sex]').val();
var age = $('input[name=age]').val();
data = {'id': id, 'name': name, 'city': city, 'sex': sex, 'age': age};
$.ajax({
type: 'PUT',
url: '/myapp/user/',
data: data,
success: function (result) {
if ( result.code === 200 ) {
alert(result.msg)
}
}
})
}
</script>
</body>
</html>
user_add.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>创建用户</title>
</head>
<body>
<h2>创建用户</h2>
<form action="/myapp/user/" method="post">
姓名:<input type="text" name="name"><br>
城市:<input type="text" name="city"><br>
性别:<input type="text" name="sex"><br>
年龄:<input type="text" name="age"><br>
<input type="submit" value="提交">
</form>
</body>
</html>
myapp/urls.py
from django.contrib import admin
from django.urls import path,include
from myapp import views
urlpatterns = [
path('user/',views.user),
path('user_list/',views.user_list),
path('user_add/',views.user_add),
path('user_edit/', views.user_edit)
]
上述是函数视图,if多分支的方式。
用django的类进行替换,类视图:
class UserView(View):
def get(self, request):
if request.GET.get('id'):
pass
# user_obj = User.objects.get(id=request.GET.get('id'))
# res = {'code': 200, 'msg': '成功!', user_obj: user_obj}
# return JsonResponse(res)
else:
user_list = User.objects.all()
return render(request, 'user_list.html', {'user_list': user_list})
def post(self, request):
name = request.POST.get('name')
city = request.POST.get('city')
sex = request.POST.get('sex')
age = request.POST.get('age')
User.objects.create(
name=name,
city=city,
sex=sex,
age=age
)
return HttpResponse("创建用户成功!")
def put(self, request):
data = QueryDict(request.body)
id = data.get('id')
user_obj = User.objects.get(id=id)
user_obj.city = data.get('city')
user_obj.sex = data.get('sex')
user_obj.age = data.get('age')
user_obj.save()
# 方式2
# data = {'city': data.get('city'), 'sex': data.get('sex'), 'age': data.get('age')}
# User.objects.filter(id=id).update(**data)
res = {'code': 200, 'msg': '更新成功!'}
return JsonResponse(res)
def delete(self, request):
data = QueryDict(request.body)
id = data.get('id')
try:
User.objects.get(id=id).delete()
res = {'code': 200, 'msg': '删除用户成功!'}
except Exception:
res = {'code': 500, 'msg': '删除用户失败!'}
return JsonResponse(res)
urls.py
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
# path('user/', views.user),
path('user/', views.UserView.as_view()), #类视图用的url地址
path('user_add', views.user_add),
path('user_edit', views.user_edit)
]