1、实现管理员列表的展示功能
models.py
class Admin(models.Model):
"""管理员"""
username = models.CharField(verbose_name="用户名",max_length=32)
password = models.CharField(verbose_name="密码",max_length=64)
工具->运行manage.py实现数据库迁移
makemigrations
migrate
打开mysql插入测试数据
insert into admin(username,password) values("codeknight","123456");
urls.py
from app01.views import depart,user,pretty,admin
path('admin/list/', admin.admin_list),
admin.py
from django.shortcuts import render, redirect
from app01 import models
from app01.utils.pagination import Pagination
def admin_list(request):
"""管理员列表"""
data_dict = {}
search_data = request.GET.get("q", "")
if search_data:
data_dict["username__contains"] = search_data
queryset = models.Admin.objects.filter(**data_dict)
page_object = Pagination(request,queryset)
contex = {
"queryset": page_object.page_queryset,
"page_string": page_object.html(),
"search_data":search_data
}
return render(request,'admin_list.html',contex)
admin_list.html
{% extends 'template.html' %}
{% block title_content %}
靓号列表
{% endblock %}
{% block content %}
<div class="container">
<!--按钮-->
<div style="margin-bottom: 10px" class="left">
<a class="btn btn-success" href="#">
<span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>
新建管理员
</a>
<!--搜索-->
<a>
<form class="navbar-form navbar-right" method="get" action="/admin/list/">
<div class="form-group">
<input type="text" class="form-control" placeholder="关键字" name="q" value="{{ search_data }}">
</div>
<button type="submit" class="btn btn-default">搜索</button>
</form>
</a>
</div>
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading">
<span class="glyphicon glyphicon-th-list" aria-hidden="true"></span>
管理员账户
</div>
<!-- Table -->
<table class="table table-bordered">
<thead>
<th>ID</th>
<th>用户名</th>
<th>密码</th>
<th>操作</th>
</thead>
<tbody>
{% for qurey in queryset %}
<tr>
<th>{{ qurey.id }}</th>
<td>{{ qurey.username }}</td>
<td>******</td>
<td>
<a class="btn btn-primary btn-xs" href="#">编辑</a>
<a class="btn btn-danger btn-xs" href="#">删除</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<!--分页组件-->
<div class="clearfix">
<ul class="pagination">
{{ page_string }}
</ul>
</div>
</div>
{% endblock %}
访问
2、实现管理员添加功能并进行密码确认
由于添加页面内容换汤不换药,所以将添加页面做一个单独的类似模板的html文件,方便重复调用 change.html
{% extends 'template.html' %}
{% block content %}
<div>
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"> {{ title }} </h3>
</div>
<div class="panel-body">
<form method="post" novalidate>
{% csrf_token %}
{% for obj in form %}
<div class="form-group">
<label> {{ obj.label }} </label>
{{ obj }}
<span style="color:red"> {{ obj.errors.0 }}</span>
</div>
{% endfor %}
<button type="submit" class="btn btn-primary"> 提交</button>
</form>
</div>
</div>
</div>
</div>
{% endblock %}
urls.py
path('admin/add/', admin.admin_add),
utils->encrypt.py
from django.conf import settings
import hashlib
def md5(data_string):
obj = hashlib.md5(settings.SECRET_KEY.encode('utf-8'))
obj.update(data_string.encode('utf-8'))
return obj.hexdigest()
utls-form.py
from django.shortcuts import render, redirect
from app01 import models
from django import forms
from django.core.exceptions import ValidationError
from app01.utils.bootstrap import BootStrapModelForm
from app01.utils.encrypt import md5
class AdminModelForm(BootStrapModelForm):
confirm_password = forms.CharField(
label="确认密码",
widget=forms.PasswordInput
)
class Meta:
model = models.Admin
fields = ["username","password","confirm_password"]
widgets = {
"password":forms.PasswordInput
}
def clean_password(self):
"""原密码加密"""
pwd = self.cleaned_data.get("password")
return md5(pwd)
def clean_confirm_password(self):
pwd = self.cleaned_data.get("password")
confirm = md5(self.cleaned_data.get("confirm_password"))
if confirm != pwd:
raise ValidationError("两次输入密码不一致")
return confirm
admin.py
from django.shortcuts import render, redirect
from app01 import models
from django import forms
from app01.utils.pagination import Pagination
from app01.utils.bootstrap import BootStrapModelForm
from app01.utils.form import AdminModelForm
def admin_list(request):
"""管理员列表"""
data_dict = {}
search_data = request.GET.get("q", "")
if search_data:
data_dict["username__contains"] = search_data
queryset = models.Admin.objects.filter(**data_dict)
page_object = Pagination(request, queryset)
contex = {
"queryset": page_object.page_queryset,
"page_string": page_object.html(),
"search_data": search_data
}
return render(request, 'admin_list.html', contex)
def admin_add(request):
"""添加管理员"""
title = "新建管理员"
if request.method == "GET":
form = AdminModelForm()
return render(request, 'change.html', {"form": form, "title": title})
form = AdminModelForm(data=request.POST)
if form.is_valid():
form.save()
return redirect("/admin/list/")
return render(request, 'change.html', {"form": form, "title": title})
访问页面
3、实现管理员同户名编辑功能
admin_list.html
<a class="btn btn-primary btn-xs" href="/admin/{{ qurey.id }}/edit/">编辑</a>
urls.py
path('admin/<int:nid>/edit/', admin.admin_edit),
form.py
class AdminEditModelForm(BootStrapModelForm):
class Meta:
model = models.Admin
fields = ['username']
admin,py
def admin_edit(request, nid):
"""编辑管理员"""
row_object = models.Admin.objects.filter(id=nid).first()
if not row_object:
return render(request, 'error.html', {"msg": "数据不存在!"})
title = "编辑管理员"
if request.method == "GET":
form = AdminEditModelForm(instance=row_object)
return render(request, "change.html", {"form": form, "title": title})
form = AdminEditModelForm(data=request.POST, instance=row_object)
if form.is_valid():
form.save()
return redirect("/admin/list/")
return render(request, "change.html", {"form": form, "title": title})
error.html
{% extends "template.html" %}
{% block content %}
<div class="container">
<div class="alert alert-danger" role="alert">{{ msg }}</div>
</div>
{% endblock %}
访问页面:
4、实现管理员列表的删除功能
urls.py
path('admin/delete/', admin.admin_delete),
admin_list.html
<a class="btn btn-danger btn-xs" href="/admin/delete/?nid={{ qurey.id }}">删除</a>
admin.py
def admin_delete(request):
nid = request.GET.get("nid")
models.Admin.objects.filter(id = nid).delete()
return redirect("/admin/list/")
访问页面: 写法2(url带参数): urls.py
path('admin/<int:nid>/delete/', admin.admin_delete),
admin.py
def admin_delete(request,nid):
"""删除管理员"""
models.Admin.objects.filter(id = nid).delete()
return redirect("/admin/list/")
admin_list.html
<a class="btn btn-danger btn-xs" href="/admin/{{ qurey.id }}/delete/">删除</a>
5、实现管理员密码的重置功能
urls.py
path('admin/<int:nid>/reset/', admin.admin_reset),
admin_list.html
{% extends 'template.html' %}
{% block title_content %}
靓号列表
{% endblock %}
{% block content %}
<div class="container">
<!--按钮-->
<div style="margin-bottom: 10px" class="left">
<a class="btn btn-success" href="/admin/add/">
<span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>
新建管理员
</a>
<!--搜索-->
<a>
<form class="navbar-form navbar-right" method="get" action="/admin/list/">
<div class="form-group">
<input type="text" class="form-control" placeholder="关键字" name="q" value="{{ search_data }}">
</div>
<button type="submit" class="btn btn-default">搜索</button>
</form>
</a>
</div>
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading">
<span class="glyphicon glyphicon-th-list" aria-hidden="true"></span>
管理员账户
</div>
<!-- Table -->
<table class="table table-bordered">
<thead>
<th>ID</th>
<th>用户名</th>
<th>密码</th>
<th>重置密码</th>
<th>操作</th>
</thead>
<tbody>
{% for query in queryset %}
<tr>
<th>{{ query.id }}</th>
<td>{{ query.username }}</td>
<td>******</td>
<td>
<a href="/admin/{{ query.id }}/reset/">重置密码</a>
</td>
<td>
<a class="btn btn-primary btn-xs" href="/admin/{{ query.id }}/edit/">编辑</a>
<!--<a class="btn btn-danger btn-xs" href="/admin/delete/?nid={ qurey.id }">删除</a>-->
<a class="btn btn-danger btn-xs" href="/admin/{{ query.id }}/delete/">删除</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<!--分页组件-->
<div class="clearfix">
<ul class="pagination">
{{ page_string }}
</ul>
</div>
</div>
{% endblock %}
form.py
class AdminResetPasswordModelForm(BootStrapModelForm):
confirm_password = forms.CharField(
label="确认密码",
widget=forms.PasswordInput
)
class Meta:
model = models.Admin
fields = ['password','confirm_password']
widgets = {
"password":forms.PasswordInput(render_value=True)
}
def clean_password(self):
"""原密码加密"""
pwd = self.cleaned_data.get("password")
md5_pwd = md5(pwd)
exists = models.Admin.objects.filter(id=self.instance.pk,password=md5_pwd).exists()
if exists:
raise ValidationError("密码不能与之前的一致!")
return md5_pwd
def clean_confirm_password(self):
pwd = self.cleaned_data.get("password")
confirm = md5(self.cleaned_data.get("confirm_password"))
if confirm != pwd:
raise ValidationError("两次输入密码不一致")
return confirm
admin.py
def admin_reset(request,nid):
"""重置管理员密码"""
row_object = models.Admin.objects.filter(id=nid).first()
if not row_object:
return redirect("/admin/list/")
title = "重置密码 - {}".format(row_object.username)
if request.method == "GET":
form = AdminResetPasswordModelForm()
return render(request, "change.html", {"form":form,"title": title})
form = AdminResetPasswordModelForm(data=request.POST,instance=row_object)
if form.is_valid():
form.save()
return redirect("/admin/list/")
return render(request, "change.html", {"form": form, "title": title})
访问页面
|