Django 创建/删除用户的示例代码

yipeiwu_com5年前Python基础

示意图:

html:

{# 用户管理 #}
  <div id="userManageDiv" style="display: none;">
    <div id="" style="margin-left: 10px;">  {# 创建用户 #}
      <h4 style="margin-top: 15px;">创建用户</h4>
      <hr style="margin-top: 5px;" />
      <div class="input-group" style="margin-bottom: 5px; margin-left: 30px; width: 253px;">
        <span class="input-group-addon" id="basic-addon1" style="width: 80px;">用户名</span>
        <input type="text" class="form-control" id="username" name="username" placeholder="请输入用户名" aria-describedby="basic-addon1" />
      </div>
      <div class="input-group" style="margin-bottom: 5px; margin-left: 30px; width: 253px;">
        <span class="input-group-addon" id="basic-addon2" style="width: 80px;">密码</span>
        <input type="password" class="form-control" id="password" name="password" placeholder="请输入密码" aria-describedby="basic-addon2" />
      </div>
      <div class="input-group" style="margin-bottom: 5px; margin-left: 30px;">
        <span class="input-group-addon" id="basic-addon3">确认密码</span>
        <input type="password" class="form-control" id="passwordAgain" name="passwordAgain" placeholder="请再次输入密码" aria-describedby="basic-addon3" />
      </div>
      <div class="input-group" style="margin-bottom: 5px; margin-left: 30px; width: 253px;">
        <span class="input-group-addon" style="width: 80px;">是否激活</span>
        <select name="userStatus" id="userStatus" class="form-control selectpicker">
          <option value="1">激活</option>
          <option value="0">封停</option>
        </select>
      </div>
      <div id="createUserAlert" class="alert alert-danger" role="alert" style="width: 30%; margin-bottom: 6px; display: none;"></div>
      <button type="button" id="createUserBtn" class="btn btn-default" data-toggle="modal" data-target="#alertTip" data-whatever="激活/封停 该账户?" style="width: 100px; margin-left: 100px;">提  交</button>
      <hr style="margin-top: 5px;" />
    </div>

    <div id="" style="margin-left: 10px; margin-top: 50px;">   {# 删除用户 #}
      <h4 style="margin-top: 15px;">删除用户</h4>
      <hr style="margin-top: 5px;" />
      <div class="input-group" style="margin-bottom: 5px; margin-left: 30px; width: 253px;">
        <span class="input-group-addon" style="width: 80px;">用户名</span>
        <select name="deleteUsername" id="deleteUsername" class="form-control selectpicker" data-live-search="true">
        {% for user in users %}
          <option value="{{ user.username }}">{{ user.username }}</option>
        {% endfor %}
        </select>
      </div>
      <button type="button" id="deleteUserBtn" class="btn btn-default" data-toggle="modal" data-target="#alertTip" data-whatever="删除 该账户?" style="width: 100px; margin-left: 100px;">提  交</button>
    </div>
  </div>

html–模态框:

{# 模态框 #}
  <div class="modal fade" tabindex="-1" role="dialog" id="alertTip">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">×</span>
          </button>
          <h4 class="modal-title">确认提示框!!</h4>
        </div>
        <div class="modal-body">
          <p id="modal_content"></p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-primary" id="modalConfirmBtn">确认</button>
          <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
        </div>
      </div>
    </div>
  </div>

前端js代码:

// 模态框 body显示
$(document).ready(function () {
  $('#alertTip').on('show.bs.modal', function (e) {
    var button = $(e.relatedTarget);
    var content = button.data('whatever');

    var modal = $(this);
    modal.find('#modal_content').text('确认 ' + content);
  })
});

// 模态框 显示前,记录 哪个div 启动了 模态框
var preAjaxDiv;
$(document).ready(function () {
  $('#createUserBtn').click(function () {
    preAjaxDiv = $(this).attr('id');
  });
  $('#deleteUserBtn').click(function () {
    preAjaxDiv = $(this).attr('id');
  });
  $('#changePasswordBtn').click(function () {
    preAjaxDiv = $(this).attr('id');
  });
  $('#changePermissionBtn').click(function () {
    preAjaxDiv = $(this).attr('id');
  });
});


// 模态框 点击确认后执行
$(document).ready(function () {
    $('#modalConfirmBtn').click(function () {
      if (preAjaxDiv == 'createUserBtn') {
        createUser();
        $('#alertTip').modal('hide');

      } else if (preAjaxDiv == 'deleteUserBtn') {
        deleteUser();
        $('#alertTip').modal('hide');

      } else if (preAjaxDiv == 'changePasswordBtn') {
        changePassword();
        $('#alertTip').modal('hide');

      } else if (preAjaxDiv == 'changePermissionBtn') {
        changePermission();
        $('#alertTip').modal('hide');
      }
    })
});

// 创建用户 激活/封停
function createUser() {
  var createUserAlert = '';
  $('#createUserAlert').hide();
  if ( !$('#username').val() ) {
    createUserAlert += "** 用户名不能为空!<br />";

  }
  if ( !$('#password').val() ) {
    createUserAlert += "** 密码不能为空!<br />";

  }
  if ( !$('#passwordAgain').val() ) {
    createUserAlert += "** 确认密码不能为空!<br />";

  }
  if ( $('#password').val() != $('#passwordAgain').val() ) {
    createUserAlert += "** 两次密码输入不一致!<br />";
  }
  if (createUserAlert) {
    $('#createUserAlert').html(createUserAlert);
    $('#createUserAlert').show();

  } else {
    $.ajax({
      url: '/createUser',
      type: 'POST',
      data: {
        createUsername: $('#username').val(),
        password: $('#password').val(),
        is_active: $('#userStatus').val()
      },
      success: function (data, textStatus) {
        if (data == 1) {
          alert('创建成功!');
          window.location.href = 'slg_manager_tem';

        } else if (data == -1) {
          alert('已经创建该账户,无法重复创建!');
        }
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert(errorThrown);
      }
    })
  }
}


// 删除用户
function deleteUser() {
  $.ajax({
    url: '/deleteUser',
    type: 'POST',
    data: {
      deleteUsername: $('#deleteUsername').val()
    },
    success: function (data, textStatus) {
      if (data == 1) {
        alert('删除成功!');
        window.location.href = 'slg_manager_tem';
      }
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      alert(errorThrown);
    }
  })
}

后端python–view视图:

# 创建用户 激活/封停
@login_required(login_url='slg:login')
@require_http_methods(["POST"])
@permission_required('slg.views_slg_manager_tem', login_url='slg:get_permissionDenied')
def create_user(request):
  username = request.POST['createUsername']
  password = request.POST['password']
  is_active = request.POST['is_active']

  createResult = db_create_user(username, password, is_active)
  if createResult == 1:
    return HttpResponse('1')
  elif createResult == -1:
    return HttpResponse('-1')

# 删除用户
@login_required(login_url='slg:login')
@require_http_methods(["POST"])
@permission_required('slg.views_slg_manager_tem', login_url='slg:get_permissionDenied')
def delete_user(request):
  username = request.POST['deleteUsername']
  deleteResult = db_delete_user(username)
  if deleteResult:
    return HttpResponse('1')

后端python–models视图:

from django.contrib.auth.models import User
from django.contrib.auth import authenticate
from django.db.utils import IntegrityError
from . import db_models as db

# 创建用户 激活/封停
def db_create_user(username, password, is_active):
  if is_active == '0':
    is_active = False
  elif is_active == '1':
    is_active = True

  try:
    User.objects.create_user(username=username, password=password, is_active=is_active)
  except IntegrityError:
    return -1  # 已经创建,无法重复创建
  else:
    return 1  # 创建成功

# 删除用户
def db_delete_user(username):
  deleteResult = User.objects.filter(username=username).delete()
  if deleteResult:
    return 1

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

在Python中操作列表之list.extend()方法的使用

 extend()方法追加序列内容到列表。 语法 以下是extend()方法的语法: list.extend(seq) 参数    ...

Django框架搭建的简易图书信息网站案例

本文实例讲述了Django框架搭建的简易图书信息网站。分享给大家供大家参考,具体如下: 创建Django项目,将数据库改为mysql,修改项目的urls.py文件 创建一个新应用,在应用...

TensorFlow卷积神经网络之使用训练好的模型识别猫狗图片

TensorFlow卷积神经网络之使用训练好的模型识别猫狗图片

本文是Python通过TensorFlow卷积神经网络实现猫狗识别的姊妹篇,是加载上一篇训练好的模型,进行猫狗识别 本文逻辑: 我从网上下载了十几张猫和狗的图片,用于检验我们训练好...

Python 通配符删除文件的实例

实例如下所示: # -*- coding: utf-8 -*- """ 使用通配符,获取所有文件,或进行操作。 """ import glob import os def files...

简单分析Python中用fork()函数生成的子进程

python的os module中有fork()函数用于生成子进程,生成的子进程是父进程的镜像,但是它们有各自的地址空间,子进程复制一份父进程内存给自己,两个进程之 间的执行是相互独立的...