# 1. 依赖于工具类 -md5_date.py
# 2. 依赖于工具类 -pagemtion.py
# 3. 依赖于工具类 -bootstrap.py
1. 创建admin表
# app --> models.py
from django.db import models
class Admin(models.Model):
"""管理员表"""
username = models.CharField(verbose_name="用户名", max_length=32)
password = models.CharField(verbose_name="密码", max_length=64)
# 关联的字段是一个对象,需要加上__str__返回字段
def __str__(self):
return self.username
2. 创建路由(url)
# 项目-->urls.py
from bbc_list.views import login, home_page, order, phone, admin
urlpatterns = [
# 管理员列表
path("admin/list/", admin.admin_list),
path("admin/add/", admin.admin_add),
path("admin/<int:nid>/update/", admin.admin_update),
path("admin/<int:nid>/delete/", admin.admin_delete),
path('admin/<int:nid>/reset/', admin.admin_reset),]
3. 创建视图函数
# app-->views-->admin.py
# 模块导入,先写内置-第三方-自定义
from django.core.exceptions import ValidationError
from django.shortcuts import render, redirect
from bbc_list import models
from bbc_list.utils.pagemtion import Pagination
from bbc_list.utils.md5_data import md5
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)
context = {
"queryset": page_object.page_queryset,
"page_string": page_object.html(),
"search_data": search_data
}
return render(request, "admin_list.html", context)
from bbc_list.utils.bootstrap import BootStrapModelForm
from django import forms
class AdminModelForm(BootStrapModelForm):
"""添加一个确认密码的输入框,这个字段在数据库里是没有的"""
confire_password = forms.CharField(label="确认密码",
# render_value=True:点击确认后不清空密码
widget=forms.PasswordInput(render_value=True) # render_value=True 定义密码保密显示
)
class Meta:
model = models.Admin
fields = ["username", "password", "confire_password"]
widgets = {
"password": forms.PasswordInput(render_value=True)
}
def clean_password(self):
"""获取密码加密"""
pwd = self.cleaned_data.get("password")
return md5(pwd)
def clean_confire_password(self):
"""钩子方法,获取密码和确认密码"""
# print(self.cleaned_data) # (self.cleaned_data) # 验证通过后,里面所有的内容
pwd = self.cleaned_data.get("password") # 此时获取的pwd就是加完秘的
confire = md5(self.cleaned_data.get("confire_password"))
if confire != pwd:
raise ValidationError("密码不一致")
return confire # return 返回的什么保存到数据库的值就是什么
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():
# {'username': 'admin', 'password': '123', 'confirm_password': '321'}
# print(form.cleaned_data) # 验证通过后,里面所有的内容
form.save()
return redirect("/admin/list/")
return render(request, "change.html", {"form": form, "title": title}) # 如果有错误的话会自动效验
class AdminUpdate(BootStrapModelForm):
class Meta:
model = models.Admin
fields = ["username"]
def admin_update(request, nid):
"""编辑"""
# 判断路径中的nid是否正确, nid / None
row_object = models.Admin.objects.filter(id=nid).first()
if not row_object:
# 方式一: 写一个提示错误的页面
# return render(request, "error.html", {"msg": "数据不存在"})
# 方式二: 跳转回首页
return redirect("/admin/list/")
title = "编辑管理员"
if request.method == "GET":
form = AdminUpdate(instance=row_object) # instance=row_object:显示默认值
return render(request, "change.html", {"form": form, "title": title}) # 如果有错误的话会自动效验
form = AdminUpdate(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}) # 如果有错误的话会自动效验
def admin_delete(reuquest, nid):
"""删除"""
models.Admin.objects.filter(id=nid).delete()
return redirect("/admin/list/")
class AdminReset(BootStrapModelForm):
# 添加一个确认密码的输入框,这个字段是数据库中没有的
confirm_password = forms.CharField(label="确认密码",
# render_value=True:点击确认后不清空密码
widget=forms.PasswordInput(render_value=True) # 定义密码密保显示
)
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_data = md5(pwd)
# 去数据库效验当前密码和新输入的密码是否一致
# self.instance就是下面代码中传入的对象 .pk:就是路径中的id
exists = models.Admin.objects.filter(id=self.instance.pk, password=md5_data).exists()
if exists:
raise ValidationError("密码不能与之前相同")
return md5_data
def clean_confirm_password(self): # 钩子方法: 获取密码和确认密码
# print(self.cleaned_data) # (self.cleaned_data) # 验证通过后,里面所有的内容
pwd = self.cleaned_data.get("password")
confirm = md5(self.cleaned_data.get("confirm_password"))
if confirm != pwd:
raise ValidationError("密码不一致")
return confirm # return 返回的什么保存到数据库的值就是什么
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 = AdminReset()
return render(request, "change.html", {"form": form, "title": title}) # 如果有错误的话会自动效验
form = AdminReset(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}) # 如果有错误的话会自动效验
4. 创建html页面
# templates-->admin_list.html
{% extends 'one.html' %}
{% block content %}
<div class="container">
<div style="margin-bottom:10px;" class="clearfix">
<a class="btn btn-success" href="/admin/add/">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
新建管理员</a>
<div style="float:right;width:300px;">
<form method="get">
<div class="input-group">
<input type="text" name="q" class="form-control" placeholder="关键字"
value="{{ search_data }}">
<span class="input-group-btn">
<button class="btn btn-default" type="submit">
<span class="glyphicon glyphicon-search" aria-hidden="true"></span>
</button>
</span>
</div>
</form>
</div>
<a class="btn btn-success" href="/phone/add/">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
新建手机号ModelForm</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>
<tr>
<th>ID</th>
<th>用户名</th>
<th>密码</th>
<th>重置密码</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for obj in queryset %}
<tr>
<th>{{ obj.id }}</th>
<th>{{ obj.username }}</th>
<th>*******</th>
<td>
<a href="/admin/{{ obj.id }}/reset/">重置密码</a>
</td>
<td>
<a class="btn btn-primary btn-xs" href="/admin/{{ obj.id }}/update/">编辑</a>
<a class="btn btn-danger btn-xs" href="/admin/{{ obj.id }}/delete/">删除</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<ul class="pagination">
{{ page_string }}
</ul>
</div>
{% endblock %}
# templates-->change.html
{% extends 'one.html' %}
{% block content %}
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">{{ title }}</h3>
</div>
<div class="panel-body">
<!-- novalidate: 关掉浏览器的校验-->
<form method="post" novalidate>
{% csrf_token %}
{% for field in form %}
<div class="form-group">
<label>{{ field.label }}</label>
<!-- <input type="text" class="form-control" placeholder="姓名" name="user">-->
{{ field }}
<span style="color:red;"> {{ field.errors.0 }}</span>
</div>
{% endfor %}
<button type="submit" class="btn btn-primary">提 交</button>
</form>
</div>
</div>
</div>
{% endblock %}
# add 和 update 和 reset 添加,修改,重置密码 都使用 change.html页面
标签:return,form,admin,09,request,列表,管理员,password,data
From: https://www.cnblogs.com/kh-1314/p/17047621.html