10.Djiango-管理员

Djiango-管理员

  • 创建管理员表 models.py
  class Admin(models.Model):
      """管理员"""
      username = models.CharField(verbose_name="用户名", max_length=32)
      password = models.CharField(verbose_name="密码", max_length=64)

  python3 manage.py makemigrations
  python3 manage.py migrate

  # INSERT INTO blog_admin(username,`password`) VALUES("tang","Tang@123");
  • 增加urls.py
  from blog.views import depart,user,pretty,admin_list

  urlpatterns = [
      # 员工管理系统-管理员
      path('admin_list/', admin_list.admin_list),
  ]
  • 增加 administrator.py
  from django.shortcuts import render, redirect
  from blog.models import Admin
  from blog.utils.pagination import Pagination

  def admin_list(req):
      """ 管理员列表 """

      # 通过get传参查询
      data_dict = {}
      search_data = req.GET.get('username', "")   # 有值拿值,没值为空
      if search_data:
          data_dict["username__contains"] = search_data

      queryset = Admin.objects.filter(**data_dict).order_by("id")

      page_obj = Pagination(req, queryset)

      context = {
          "admin_list": page_obj.page_queryset,
          "page_string": page_obj.html()
      }

      return render(req, "admin_list.html", context)
  • 增加admin_list.html
  {% extends 'layout.html' %}

  {% block content %}
  <div class="container">
    <div>
      <div class="row">
        <div class="col-lg-6">
          <div class="input-group">
            <a href="/admin_add/">
              <button class="btn btn-success"><span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>
                新增管理员</button>
            </a>
            </span>
          </div>
        </div>
        <div class="col-lg-6">
          <form method="get" action="/admin_list/">
            <div class="input-group">
              <input type="text" class="form-control" placeholder="查询用户名" name="username" value="{{ search_data }}">
              <span class="input-group-btn">
                <button class="btn btn-primary" type="submit"><span class="glyphicon glyphicon-search"
                    aria-hidden="true"></span><strong> 搜索</strong></button>
              </span>
            </div>
          </form>
        </div>
      </div>
    </div>
    <div style="margin-top: 20px;">
      <div class="panel panel-default">
        <div class="panel-heading">
          <strong>
            <span class="glyphicon glyphicon-th-list" aria-hidden="true"></span> 管理员列表
          </strong>
        </div>
        <table class="table table-bordered">
          <thead>
            <tr>
              <th>ID</th>
              <th>用户名</th>
              <th>密码</th>
            </tr>
          </thead>
          <tbody>
            {% for iteam in admin_list %}
            <tr>
              <th scope="row">{{ iteam.id }}</th>
              <td>{{ iteam.username }}</td>
              <td>{{ iteam.password }}</td>
              <td>
                <a class="btn btn-primary btn-xs" href="/admin/{{ iteam.id }}/edit/"> 编辑 </a>
                <a class="btn btn-danger btn-xs" href="/admin/{{ iteam.id }}/del/"> 删除 </a>
              </td>
            </tr>
            {% endfor %}
          </tbody>
        </table>
      </div>
    </div>
    <nav aria-label="page">
      <ul class="pagination">
        {{ page_string }}
        <form method="get" action="/admin_list/">
          <div class="input-group col-sm-2" style="display: inline-block;margin-left: 20px;">
            <span class="input-group-btn">
              <input type="text" class="form-control" placeholder="页面跳转" name="page">
              <button class="btn btn-primary" type="submit">>> 跳转</button>
            </span>
          </div>
        </form>
      </ul>
    </nav>
  </div>
  {% endblock %}

新增

  • form.py 增加密码再确认、密码复制度验证、md5密码加密

    # 新增管理员 modelform
    class AdminModelForm(BootStrapModelForm):
      confirm_password = forms.CharField(
          label="确认密码", widget=forms.PasswordInput(render_value=True))
          # PasswordInput(render_value=True) 验证不能过密码不会重置为空
    
      class Meta:
          model = Admin
          fields = ["username", "password", "confirm_password"]
          # fields = "__all__"    # 所有字段
          # exclude = ['level']   # 排除字段
    
          widgets = {
              "password": forms.PasswordInput(attrs={"placeholder": "密码:大小写字符|数字|特殊字符|8位以上"}, render_value=True),
          }
    
      # 密码复杂度验证与MD5加密
      def clean_password(self):
          # from blog.utils.password import check_fips_password_complexity
          # from blog.utils.encrypt import md5
    
          pwd = self.cleaned_data.get("password")
    
          if check_fips_password_complexity(pwd) == True:
              return md5(pwd)
          else:
              str = check_fips_password_complexity(pwd)
              raise ValidationError(str)
    
      # 数据验证 方式二 钩子方法
      def clean_confirm_password(self):
          # from blog.utils.encrypt import md5
    
          # print(self.cleaned_data)
          pwd = self.cleaned_data.get("password")   # 已md5加密
          confirm = md5(self.cleaned_data.get("confirm_password"))
    
          # 检查两次输入的密码是否一致
    
          if confirm != pwd:
              raise ValidationError("两次输入的密码不一致")
    
          # 验证完成后return该字段数据会保存至数据库,所以需要return原数据
          return confirm  # 验证通过
  • administrator.py

    def admin_add(req):
      if req.method == "GET":
          form = AdminModelForm()
    
          context = {
              "form": form,
              "form_add_title": "新建管理员"
          }
    
          return render(req, "form_add.html", context)
    
      try:
          form = AdminModelForm(data=req.POST)
          if form.is_valid():
              # print(form.cleaned_data) # {'username': 'haha', 'password': '123', 'confirm_password': '1234'}
              form.save()
              return redirect("/admin_list/")
    
          context = {
              "form": form,
              "form_add_title": "新建管理员"
          }
    
          return render(req, "form_add.html", context)
      except Exception as e:
          form = AdminModelForm(data=req.POST)
          context = {
              "form": form,
              "form_add_title": "新建管理员",
              "error_msg": e
          }
          return render(req, "form_add.html", context)
  • form_add.html

    {% extends 'layout.html' %}
    
    {% block content %}
    <div class="container">
      <hr>
      </hr>
      <div class="panel panel-default">
          <div class="panel-heading">
              <h3 class="panel-title"><strong>{{ form_add_title }}</strong></h3>
          </div>
          <div class="panel-body">
              <form class="form-group" method="post" novalidate>
                  {% csrf_token %}
    
                  {% for field in form %}
                  <div class="form-group">
                      <label>{{ field.label }}: </label>
                      {{ field }}
                      <!-- 数据校验,显示错误信息 -->
                      <span style="color: red;">{{ field.errors.0 }}</span>
                  </div>
                  {% endfor %}
                  <div class="form-group">
                      <button type="submit" class="btn btn-success"><span class="glyphicon glyphicon-plus"
                              aria-hidden="true"></span><strong> 提 交</strong></button>
                  </div>
                  <br>
                  <span style="color: red;"> {{ error_msg }} </span>
              </form>
          </div>
      </div>
    </div>
    {% endblock %}

编辑

  • form.py

    # 编辑管理员 modelform
    class AdminEditModelForm(BootStrapModelForm):
    
      class Meta:
          model = Admin
          fields = ["username", "password"]
          # fields = "__all__"    # 所有字段
          # exclude = ['level']   # 排除字段
          labels={"username":"姓名"}     # 为name字段添加标签说明,如果不设置标签,则在页面上显示的为数据库字段本身的名字
          help_texts={"username":"姓名为中英文字符串"}  # 为username字段添加和帮助文本说明
    
          widgets = {
              "password": forms.PasswordInput(attrs={"placeholder": "密码:大小写字符|数字|特殊字符|8位以上", "value": ""}, render_value=True),
          }
    
      # 密码复杂度验证与MD5加密
      def clean_password(self):
          # from blog.utils.password import check_fips_password_complexity
          # from blog.utils.encrypt import md5
    
          pwd = self.cleaned_data.get("password")
    
          if check_fips_password_complexity(pwd) == True:
              return md5(pwd)
          else:
              str = check_fips_password_complexity(pwd)
              raise ValidationError(str)
  • administrator.py

    # 创建 admin_edit 函数
    def admin_edit(req, nid):
      row_obj = Admin.objects.filter(id=nid).first()
    
      if not row_obj:
          # return redirect("/admin_list/")
          return render(req, 'error.html', { "error_msg": "数据不存在!"})
    
      # GET
      if req.method == "GET":
          form = AdminEditModelForm(instance=row_obj)
          context = {
              "form": form,
              "form_add_title": "编辑管理员",
              # "confirm_password_value": row_obj.password
              }
          return render(req, "form_edit_pwd.html", context)
    
      # POST
      form = AdminEditModelForm(data=req.POST, instance=row_obj)
      context = {
      "form": form,
      "form_add_title": "编辑管理员",
      # "confirm_password_value": row_obj.password
      }
      if form.is_valid():
          form.save()
          return redirect("/admin_list/")
    
      return render(req, "form_edit_pwd.html", context) 
  • form_edit_pwd.html
    • 同新增——form_add.html

删除

# urls.py
path('admin_del/<int:nid>/', administrator.admin_del),
# admin_del函数
def admin_del(req, nid):
    Admin.objects.filter(id=nid).delete()
    return redirect("/admin_list/")
<a class="btn btn-danger btn-xs" href="/admin_del/{{ iteam.id }}/"> 删除 </a>

重置密码

  • urls.py
    path('admin_pwd_reset/<int:nid>/', administrator.admin_pwd_reset),
  • form.py

    # 重置管理员密码 modelform
    class AdminResetModelForm(BootStrapModelForm):
      confirm_password = forms.CharField(
          label="确认密码", widget=forms.PasswordInput(render_value=True))
      # PasswordInput(render_value=True) 验证不能过密码不会重置为空
    
      class Meta:
          model = Admin
          fields = ["password", "confirm_password"]
          # fields = "__all__"    # 所有字段
          # exclude = ['level']   # 排除字段
    
          widgets = {
              "password": forms.PasswordInput(attrs={"placeholder": "密码:大小写字符|数字|特殊字符|8位以上"}, render_value=True),
          }
    
      # 密码复杂度验证与MD5加密
      def clean_password(self):
          # from blog.utils.password import check_fips_password_complexity
          # from blog.utils.encrypt import md5
    
          pwd = self.cleaned_data.get("password")
    
          if check_fips_password_complexity(pwd) == True:
    
              # 重置密码不可与原密码一致,去数据库检验当前与密码与原密码
              md5_pwd = md5(pwd)
              exists = Admin.objects.filter(
                  id=self.instance.pk, password=md5_pwd).exists()
              if exists:
                  raise ValidationError("新密码不可与原密码一致!")
    
              return md5_pwd
    
      # 数据验证 方式二 钩子方法
      def clean_confirm_password(self):
          # from blog.utils.encrypt import md5
          # str = self.clean_password(self)
          # print(str)
          # print(self.cleaned_data)
          pwd = self.cleaned_data.get("password")   # 已md5加密
          confirm = md5(self.cleaned_data.get("confirm_password"))
    
          # 检查两次输入的密码是否一致
          if confirm != pwd:
              raise ValidationError("两次输入的密码不一致")
    
          # 验证完成后return该字段数据会保存至数据库,所以需要return原数据
          return confirm  # 验证通过
  • administrator.py

    # 创建 admin_pwd_reset 函数
    def admin_pwd_reset(req, nid):
      row_obj = Admin.objects.filter(id=nid).first()
    
      if not row_obj:
          # return redirect("/admin_list/")
          return render(req, 'error.html', { "error_msg": "数据不存在!"})
    
      # GET
      if req.method == "GET":
          form = AdminResetModelForm()    # 不填充数据
          context = {
              "form": form,
              "form_add_title": "重置管理员 {} 的密码".format(row_obj.username),
              }
          return render(req, "form_edit_pwd.html", context)
    
      # POST
      form = AdminResetModelForm(data=req.POST, instance=row_obj)
      context = {
      "form": form,
      "form_add_title": "重置管理员 {} 的密码".format(row_obj.username),
      }
      if form.is_valid():
          form.save()
          return redirect("/admin_list/")
    
      return render(req, "form_edit_pwd.html", context)
  • admin_list.html
    <a class="btn btn-warning btn-xs" href="/admin_pwd_reset/{{ iteam.id }}/"> 重置密码 </a>