基于Django 框架的用户管理(用户显示,用户新增,用户修改,用户删除),密码加密与检验

做web应用肯定少不了,用户的管理(增删改查)等操作
第一步:分析我们需要的字段,进行建模

models.py
----
class teuser(models.Model):
    username = models.CharField(max_length=255)
    password = models.CharField(max_length=255)
    email = models.CharField(max_length=255)

第二步:执行命令生成数据表
python manage.py makemigrations
python manage.py migrate
第三部:写代码

#导入模块
from django.contrib.auth.hashers import make_password, check_password   #密码加密&解密
from django.views.decorators.csrf import csrf_exempt #跨域访问
from store.models import teuser #导入models
from django.http import HttpResponse

# 创建用户 
@csrf_exempt
def create_user(request):
    #get请求就返回创建用户页面
    if request.method == 'GET':
        return render(request, 'createuser.html')
     #post请求就执行创建操作
    elif request.method == 'POST':
        try:
            username = request.POST.get('createUsername')
            password = request.POST.get('password')
            email = request.POST.get('email')
            # 明文密码经过加密处理
            passwords = make_password(password,None,'pbkdf2_sha256')
            print('getpassword is value:',passwords)
            createResult = teuser.objects.create(username = username,password = passwords,email = email)
            #createResult. set_password(passwords)
            createResult.save()
            return HttpResponse('1')
        except:
            return HttpResponse('-1')
# 删除用户
@csrf_exempt
def delete_user(request,id):
    if request.method == 'GET':
        try:
            result = teuser.objects.filter(id=id)
            result.delete()
            return HttpResponse('success')
        except:
            return HttpResponse('fail')
#获取修改用户的页面
def editUser(request,id):
    if request.method == 'GET':
        #result = User.objects.filter(id)
        result = teuser.objects.filter(id=id)
        #print("需要修改的用户名为:".format(result))
        template = get_template('updateuser.html')
        html = template.render({'content': result})
        return HttpResponse(html)
# 修改密码
###思路:获取前台页面的数据,把获取到的password跟数据库查询值指定的password进行比对,是true就执行修改操作,是false就弹框###
@csrf_exempt
def change_password(request):
    if request.method == 'POST':
        try:
            username = request.POST.get('username')
            oldPassword = request.POST.get('oldPassword')
            newPassword = request.POST.get('newPassword')
            name = teuser.objects.filter(username=username)
            for item in name:
                getpwd = item.password
                #判断获取到的密码跟数据库的密码是否一致
                ck = check_password(oldPassword, getpwd)
                if ck:
                    cknewpassword = make_password(newPassword, None, 'pbkdf2_sha256')
                    #新密码进行加密并修改保存在数据库
                    item.password = cknewpassword
                    item.save()
                    return HttpResponse('1')
                else:
                    return HttpResponse('-1')
        except Exception as e:
           print(e)
        return HttpResponse('-1')
#用户列表
def listUser(request):
    #查询用户所有的数据
    result = teuser.objects.all()
    template = get_template('list.html')
    html = template.render({'content':result})
    return HttpResponse(html)

urls.py

url(r'^createUser/$',views.create_user,name='createUser'),
#(.+)指传参数
url(r'^deleteUser/(.+)/$',views.delete_user,name='deleteUser'),
url(r'^changePassword/$',views.change_password,name='changePassword'),
url(r'^editUser/(.+)/$',views.editUser,name='editUser'),
url(r'^listUser/$',views.listUser,name='listUser'),

第四步:页面html代码
list.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <a href="/createUser">创建用户</a>
     <table border="1" text-align="center">
    <thead>
    <tr>
        <th>编号</th>
        <th>用户名</th>
        <th>密码</th>
        <th>邮箱</th>
        <th>操作</th>
    </tr>
    </thead>
    <tbody>
    {#    这里是模板语言,for循环,最后需要 endfor#}
    {% for foo in content %}
        <tr>
            <td>{{ foo.id }}</td>
            <td>{{ foo.username }}</td>
            <td>{{ foo.password }}</td>
            <td>{{ foo.email }}</td>
            <td><a href="{% url 'editUser' foo.id%}">修改</a></td>
            <td><a href="{% url 'deleteUser' foo.id%}">删除</a></td>
        </tr>
    {% endfor %}
    </tbody>
</table>
</body>
</html>

createuser.html页面中引入了jquery脚本,如果不知道怎么配置的,请点击:https://blog.csdn.net/tyt_XiaoTao/article/details/80209933

{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户管理</title>
</head>
<body>
        <div id="userManageDiv">
        <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" id="basic-addon3">邮箱地址</span>
                <input type="text" class="form-control" id="email" name="passwordAgain" placeholder="请输入邮箱" aria-describedby="basic-addon3" />
            </div>
            <div id="createUserAlert" class="alert alert-danger" role="alert" style="width: 30%; margin-bottom: 6px;"></div>
            <button type="button" id="createUserBtn" class="btn btn-default" data-toggle="modal" data-target="#alertTip" data-whatever="激活/封停 该账户?" style="width: 100px; margin-left: 100px;">提&nbsp;&nbsp;交</button>
            <hr style="margin-top: 5px;" />
        </div>
<script type="text/javascript" src="{% static "/js/jquery-3.3.1.min.js" %}"></script>
<script type="text/javascript">
    $(function () {
        $("#createUserBtn").click(function () {
            var createUserAlert = '';
            if (!$('#username').val()) {
                createUserAlert += "**  用户名不能为空!<br />";
                alert("用户名不能为空!")
                return false;
            }
            if (!$('#password').val()) {
                createUserAlert += "**  密码不能为空!<br />";
                alert("密码不能为空!")
                return false;
            }
            if (!$('#passwordAgain').val()) {
                createUserAlert += "**  确认密码不能为空!<br />";
                alert("确认密码不能为空!")
                return false;
            }
            if ($('#password').val() != $('#passwordAgain').val()) {
                createUserAlert += "**  两次密码输入不一致!<br />";
                alert("两次密码输入不一致!")
                return false;
            }
            $.ajax({
                url: '/createUser/',
                type: 'POST',
                data: {
                    createUsername: $('#username').val(),
                    password: $('#password').val(),
                    email: $('#email').val()
                },
                success: function (data, textStatus) {
                    console.log(data);
                    if (data == 1) {
                        alert('创建成功!');
                        window.location.href = '/listUser';

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

updateuser.html

{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>修改密码</title>
</head>
<body>
    <div id="changePasswordDiv" style="margin-left: 20px; margin-top: 20px;">
         {% for foo in content %}
            <div class="input-group" style="margin-bottom: 5px; width: 253px;">
                <span class="input-group-addon" style="width: 80px;">用户名</span>
                <input type="text" name="" id="loginUsername" value="{{ foo.username }}" class="form-control" readonly disabled/>
            </div>
        {% endfor %}
        <div class="input-group" style="margin-bottom: 5px; width: 253px;">
            <span class="input-group-addon" style="width: 80px;">旧密码</span>
            <input type="password" name="oldPassword" id="oldPassword" class="form-control" />
        </div>
        <div class="input-group" style="margin-bottom: 5px; width: 253px;">
            <span class="input-group-addon" style="width: 80px;">新密码</span>
            <input type="password" name="newPassword" id="newPassword" class="form-control" />
        </div>
        <div class="input-group" style="margin-bottom: 5px; width: 253px;">
            <span class="input-group-addon" style="width: 80px;">确认密码</span>
            <input type="password" name="newPasswordAgain" id="newPasswordAgain" class="form-control" />
        </div>
        <div id="changePasswordAlert" class="alert alert-danger" role="alert" style="width: 30%; margin-bottom: 6px; display: none;"></div>
        <button type="button" id="changePasswordBtn" class="btn btn-default" data-toggle="modal" data-target="#alertTip" data-whatever="重置密码?" style="width: 100px; margin-left: 70px;">提&nbsp;&nbsp;交</button>
    </div>
 <script type="text/javascript" src="{% static "/js/jquery-3.3.1.min.js" %}"></script>
<script type="text/javascript">
    $(function () {
        $('#changePasswordBtn').click(function () {
            var changePasswordAlert = '';
            //$('#changePasswordAlert').hide();
            if (!$('#oldPassword').val()) {
                //changePasswordAlert += '**  旧密码不能为空!<br />';
                alert('旧密码不能为空!');
                return false;
            }
            if (!$('#newPassword').val()) {
                //changePasswordAlert += '**  新密码不能为空!<br />';
                alert('新密码不能为空!')
                return false;
            }
            if (!$('#newPasswordAgain').val()) {
                //changePasswordAlert += '**  确认密码不能为空!<br />';
                alert('确认密码不能为空!')
                return false;
            }
            if ($('#newPassword').val() != $('#newPasswordAgain').val()) {
                //changePasswordAlert += '**  两次密码不一致!<br />';
                alert('两次密码不一致!');
                return false;
            }
            if ($('#oldPassword').val() == $('#newPasswordAgain').val()) {
                //changePasswordAlert += '**  新密码和旧密码不能一样!<br />';
                alert('新密码和旧密码不能一样!')
                return false;
            }
            $.ajax({
                url: '/changePassword/',
                type: 'POST',
                data: {
                    username: $('#loginUsername').val(),
                    oldPassword: $('#oldPassword').val(),
                    newPassword: $('#newPassword').val()
                },
                success: function (data, textStatus) {
                    if (data == 1) {
                        alert('修改成功!');
                        window.location.href = '/listUser';

                    } else if (data == -1) {
                        alert('旧密码错误!');

                    } else if (data == 0) {
                        alert('没有相关权限!');
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(errorThrown);
                }
            })
        })
    })
</script>
</body>
</html>

页面展示:(ps:删除的时候,没有做页面优化,所有导致删除后得重新刷新页面加载数据);GitHub的传送门:https://github.com/xt998/mysite
这里写图片描述

猜你喜欢

转载自blog.csdn.net/tyt_XiaoTao/article/details/80335107