作业:
在浏览器页面展示用户表,能修改用户信息,删除用户和新增用户,内部原理必须利用无名有名反向解析完成数据的增删改查。
路由层:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^userlist/',views.userlist),
url(r'^edit/(d+)/',views.edit,name='xxx'),
url(r'^delete/(?P<delete_id>d+)/',views.delete,name='ooo'),
url(r'^create_user/(?P<create_user>d+)/',views.create_user,name='aaa'),
]
视图层:
from django.shortcuts import render, reverse, redirect
from app01 import models
# Create your views here.
# 1.展示用户表视图函数
def userlist(request):
user_queryset = models.User.objects.all()
if request.method == 'POST':
...
return render(request, 'userlist.html', locals())
# 2.编辑视图函数
def edit(request, edit_id):
edit_obj = models.User.objects.filter(id=edit_id).first()
reverse('xxx', args=(edit_id,))
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
edit_obj.username = username
edit_obj.password = password
edit_obj.save()
return redirect('/userlist/')
return render(request, 'edit_user.html', locals())
# 3.删除视图函数
def delete(request, delete_id):
reverse('xxx', args=(delete_id,))
models.User.objects.filter(id=delete_id).delete()
return redirect('/userlist/')
# 4.新增用户视图函数
def create_user(request, create_user):
reverse('aaa', args=(create_user,))
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user_obj = models.User(username=username, password=password)
user_obj.save()
return redirect('/userlist/')
return render(request, 'create_user.html', locals())
模版层:
-
展示数据页面(
userlist.html
)<div class="col-md-8 col-md-offset-2"> <table class="table table-bordered table-striped"> <tbody> {% for user_obj in user_queryset %} <tr> <td>{{ user_obj.id }}</td> <td>{{ user_obj.username}}</td> <td>{{ user_obj.password }}</td> <td> <a href="{% url 'xxx' user_obj.id %}" class="btn btn-success btn-xs " >编辑</a> <a href="{% url 'ooo' user_obj.id %}" class="btn btn-danger btn-xs">删除</a> </td> </tr> {% endfor %} </tbody> </table> <a href="{% url 'aaa' 111 %}" class="btn btn-primary btn-block" >新增</a> </div>
-
编辑页面(
edit_user.html
)<div class="container"> <h1 class="text-center">编辑</h1> <div class="row"> <div class="col-md-8 col-md-offset-2"> <form action="" method="post"> <p>用户名<input type="text" value="{{ edit_obj.username}}" class="form-control" name="username"></p> <p>密码<input type="password" value="{{ edit_obj.password}}" class="form-control" name="password"></p> <p><input type="submit" value="编辑" class="form-control btn btn-success btn-block"></p> </form> </div> </div> </div>
-
新增用户页面(
create_user.html
)<div class="container"> <h1 class="text-center">新增用户</h1> <div class="row"> <div class="col-md-8 col-md-offset-2"> <form action="" method="post"> <p>用户名<input type="text" value="输入用户名" class="form-control" name="username"></p> <p>密码<input type="password" class="form-control" name="password"></p> <p><input type="submit" value="增加" class="form-control btn btn-success btn-block"></p> </form> </div> </div> </div>