Django实战项目-学习任务系统-用户管理
接着上期代码框架,开发第6个功能,用户管理,查看用户信息和学生用户属性值,尤其是总积分值,还可以查看积分流水明细,完成任务奖励积分,兑换物品消耗积分。
第一步:编写第6个功能-用户管理
1,编辑模型文件:
./mysite/study_system/models.py:
无新增模型
2,编辑urls配置文件:
./mysite/study_system/urls.py
# 用户管理url path('user/getUserInfo/', views.getUserInfo, name='getUserInfo'), path('user/toModUserInfo/', views.toModUserInfo, name='toModUserInfo'), path('user/updateUserInfo/', views.updateUserInfo, name='updateUserInfo'), # 积分流水url path('item/getStudyPointsList/', views.getStudyPointsList, name='getStudyPointsList'),
3,编辑视图文件:
./mysite/study_system/views.py
def getUserInfo(request): ''' @方法名称: 用户管理视图 @作 者: PandaCode辉 @weixin公众号: PandaCode辉 @创建时间: 2023-10-10 ''' # 响应容器 rsp_dict = {} # 获取当前用户名 username = request.session.get('username') # 根据用户名获取用户对象 cur_user = StudyUser.objects.get(username=username) print('根据用户名查询用户对象:' + str(cur_user)) try: # 学生用户总积分值,需要取学生用户,关联的属性表的值 cur_user_attr = StudyUserAttribute.objects.get(user_id=cur_user) rsp_dict['cur_user_attr'] = cur_user_attr except Exception as e: print('根据用户名查询属性表,查无记录.') template_name = "study_system/home.html" rsp_dict["pageTitle"] = "用户信息" rsp_dict['html_file'] = 'study_system/user/userInfo.html' rsp_dict['cur_user'] = cur_user return render(request, template_name, rsp_dict) def toModUserInfo(request): ''' @方法名称: 跳转到修改用户视图 @作 者: PandaCode辉 @weixin公众号: PandaCode辉 @创建时间: 2023-10-10 ''' # 响应容器 rsp_dict = {} rest = request.GET user_id = rest['userId'] # 根据用户名获取用户对象 cur_user = StudyUser.objects.get(user_id=user_id) print('查询用户对象:' + str(cur_user)) try: # 学生用户总积分值,需要取学生用户,关联的属性表的值 cur_user_attr = StudyUserAttribute.objects.get(user_id=cur_user) rsp_dict['cur_user_attr'] = cur_user_attr except Exception as e: print('根据用户名查询属性表,查无记录.') rsp_dict["pageTitle"] = "修改用户" rsp_dict['html_file'] = 'study_system/user/updateUserInfo.html' rsp_dict['cur_user'] = cur_user return render(request, "study_system/home.html", rsp_dict) def updateUserInfo(request): ''' @方法名称: ajax请求, 表单视图,更新用户信息 @作 者: PandaCode辉 @weixin公众号: PandaCode辉 @创建时间: 2023-10-10 ''' # 初始化响应容器 rsp_dict = {"result": "error", "errorMsg": "系统错误"} # 是否ajax请求 if request.is_ajax(): try: rest = request.POST # 用户值 user_id = int(rest['userId']) username = rest['userName'] password = rest['password'] email = rest['email'] phone_num = rest['phoneNum'] role = int(rest['role']) # 根据ID查询对象数据, filter 返回的是列表对象,一个对象取list.0 studyUser = StudyUser.objects.filter(user_id=user_id) # 今天 # UTC格式当前时区时间 t = time.localtime() work_date = time.strftime("%Y-%m-%d %H:%M:%S", t) print('当前日期时间:' + str(work_date)) # 保存到数据库是否成功,更新用户表 studyUser.update(username=username, password=password, email=email, phone_num=phone_num, update_time=work_date) print('更新用户表成功.') # 属性值 study_level = int(rest['studyLevel']) # 用户属性值,学习级别,不为空,则更新属性值 if study_level != "": # 属性值 study_level = int(rest['studyLevel']) intelligence = int(rest['intelligence']) memory = int(rest['memory']) diligence = int(rest['diligence']) physical_fitness = int(rest['physicalFitness']) other_subjects = rest['otherSubjects'] notes = rest['notes'] # 根据用户名获取用户对象 cur_user = StudyUser.objects.get(user_id=user_id) # print('查询用户对象:' + str(cur_user)) # 学生用户总积分值,需要取学生用户,关联的属性表的值 studyUserAttribute = StudyUserAttribute.objects.filter(user_id=cur_user) # 保存到数据库是否成功,更新用户属性表 studyUserAttribute.update(study_level=study_level, intelligence=intelligence, memory=memory, diligence=diligence, physical_fitness=physical_fitness, other_subjects=other_subjects, notes=notes, update_time=work_date) print('更新用户属性表成功.') rsp_dict["result"] = "success" except Exception as e: rsp_dict["errorMsg"] = "更新用户信息,保存到数据库失败." # 成功与否都返回json数据格式 return JsonResponse(rsp_dict) def getStudyPointsList(request): ''' @方法名称: 获取积分明细列表 @作 者: PandaCode辉 @weixin公众号: PandaCode辉 @创建时间: 2023-10-10 ''' # 响应容器 rsp_dict = {} # 获取当前用户名 username = request.session.get('username') # 根据用户名获取用户对象 cur_user = StudyUser.objects.get(username=username) print('根据用户名查询用户对象:' + str(cur_user)) #查询积分列表 data_list = StudyPoint.objects.filter(user_id=cur_user).order_by('-created_time') rsp_dict['data_list'] = data_list context_object_name = "study_points_list" template_name = "study_system/home.html" rsp_dict['html_file'] = 'study_system/item/studyPointsList.html' rsp_dict['context_object_name'] = context_object_name return render(request, template_name, rsp_dict)
4,编辑页面模板代码:
4.1. 用户管理页面
./mysite/study_system/templates/study_system/user/userInfo.html
<!-- 结果显示区 --> <div id="dataList"> {% if cur_user %} <ul class="dataCardList"> <li>【用户ID :{{ cur_user.user_id }}】</li> <li>【用户名 :{{ cur_user.username }}】</li> <li>【邮箱 : {{ cur_user.email }}】</li> <li>【手机号码 : {{ cur_user.phone_num }}】</li> {% if cur_user.role == 1 %} <li>【角色 :系统管理员 】</li> {% elif cur_user.role == 2 %} <li>【角色 :辅导员 】</li> {% elif cur_user.role == 3 %} <li>【角色 :学生 】</li> {% elif cur_user.role == 4 %} <li>【角色 :自导自学 】</li> {% endif %} {# 学生用户属性值#} {% if cur_user_attr %} {% if cur_user_attr.study_level == 1 %} <li>【级别 :Lv1-小学 】</li> {% elif cur_user_attr.study_level == 2 %} <li>【级别 :Lv2-初中 】</li> {% elif cur_user_attr.study_level == 3 %} <li>【级别 :Lv3-高中 】</li> {% elif cur_user_attr.study_level == 4 %} <li>【级别 :Lv4-本科 】</li> {% elif cur_user_attr.study_level == 5 %} <li>【级别 :Lv5-硕士 】</li> {% elif cur_user_attr.study_level == 6 %} <li>【级别 :Lv6-博士 】</li> {% elif cur_user_attr.study_level == 7 %} <li>【级别 :Lv7-博士后 】</li> {% endif %} <li>【智力 :{{ cur_user_attr.intelligence }} 点】</li> <li>【记忆力 :{{ cur_user_attr.memory }} 点】</li> <li>【勤奋力 :{{ cur_user_attr.diligence }} 点】</li> <li>【体能 :{{ cur_user_attr.physical_fitness }} 点】</li> <li class="strongTab"> <span>【总积分 :{{ cur_user_attr.total_points }} 点】 <a href="/study_system/item/getStudyPointsList/">积分明细</a> </span> </li> <li>【学科属性 :{{ cur_user_attr.other_subjects }}】</li> <li class="strongTab">【备注提醒 :{{ cur_user_attr.notes }}】</li> {% endif %} <li>【更新时间 :{{ cur_user.update_time| date:'Y-m-d H:i:s' }}】</li> <li> <a href="/study_system/user/toModUserInfo?userId={{ cur_user.user_id }}" class="btn btn-default btn-lg btn-block btn-a">修改用户信息</a> </li> </ul> {% else %} <strong>查无记录</strong> {% endif %} </div>
4.2. 修改用户信息页面
./mysite/study_system/templates/study_system/user/updateUserInfo.html
<script type="text/javascript"> function updateUserInfo() { var userId = $("input[name='userId']").val(); var userName = $("input[name='userName']").val(); var password = $("input[name='password']").val(); var email = $("input[name='email']").val(); var phoneNum = $("input[name='phoneNum']").val(); var role = $("select[name='role']").val(); var studyLevel = ""; var intelligence = ""; var memory = ""; var diligence = ""; var physicalFitness = ""; var otherSubjects = ""; var notes = ""; var cur_user_attr = '{{ cur_user_attr }}'; // 用户属性不为空时 if (cur_user_attr) { studyLevel = $("select[name='studyLevel']").val(); intelligence = $("input[name='intelligence']").val(); memory = $("input[name='memory']").val(); diligence = $("input[name='diligence']").val(); physicalFitness = $("input[name='physicalFitness']").val(); otherSubjects = $("textarea[name='otherSubjects']").val(); notes = $("textarea[name='notes']").val(); } var csrf_token = '{{ csrf_token }}'; $.post("/study_system/user/updateUserInfo/", { 'userId': userId, 'userName': userName, 'password': password, 'email': email, 'phoneNum': phoneNum, 'role': role, 'studyLevel': studyLevel, 'intelligence': intelligence, 'memory': memory, 'diligence': diligence, 'physicalFitness': physicalFitness, 'otherSubjects': otherSubjects, 'notes': notes, // 将token值放到请求数据部分,token的键必须是 csrfmiddlewaretoken 'csrfmiddlewaretoken': csrf_token, }, function (data) { if ("success" == data.result) { alert("更新成功"); window.location.href = "/study_system/user/getUserInfo/"; } else { alert("更新失败:" + data.errorMsg); } }); } </script> <div class="container"> <h1 class="text-center">更新用户信息</h1> {% if cur_user %} <form action="/study_system/user/updateUserInfo/" method="post" class="form-horizontal" role="form"> {% csrf_token %} <div class="form-group"> <label for="userId" class="col-sm-2 control-label">用户ID</label> <div class="col-sm-10"> <input type="text" class="form-control" name="userId" id="userId" value='{{ cur_user.user_id }}' readonly="readonly"> </div> </div> <div class="form-group"> <label for="userName" class="col-sm-2 control-label">用户名</label> <div class="col-sm-10"> <input type="text" class="form-control" name="userName" id="userName" value='{{ cur_user.username }}' readonly="readonly"> </div> </div> <div class="form-group"> <label for="password" class="col-sm-2 control-label">密码</label> <div class="col-sm-10"> <input type="password" class="form-control" name="password" id="password" value='{{ cur_user.password }}'> </div> </div> <div class="form-group"> <label for="email" class="col-sm-2 control-label">密码</label> <div class="col-sm-10"> <input type="email" class="form-control" name="email" id="email" value='{{ cur_user.email }}'> </div> </div> <div class="form-group"> <label for="phoneNum" class="col-sm-2 control-label">手机号码</label> <div class="col-sm-10"> <input type="text" class="form-control" name="phoneNum" id="phoneNum" value='{{ cur_user.phone_num }}'> </div> </div> <div class="form-group"> <label for="role" class="col-sm-2 control-label">角色</label> <div class="col-sm-10"> <select class="form-control" name="role" id="role"> {% if cur_user.role == 1 %} <option value="1" selected="selected">1-系统管理员</option> {% elif cur_user.role == 2 %} <option value="2" selected="selected">2-辅导员</option> {% elif cur_user.role == 3 %} <option value="3" selected="selected">3-学生</option> {% elif cur_user.role == 4 %} <option value="4" selected="selected">4-自导自学</option> {% endif %} </select> </div> </div> {# 学生用户属性值#} {% if cur_user_attr %} <h1 class="text-center">更新用户属性值</h1> <div class="form-group"> <label for="studyLevel" class="col-sm-2 control-label">学习级别</label> <div class="col-sm-10"> <select class="form-control" name="studyLevel" id="studyLevel"> <option value="1">Lv1-小学</option> <option value="2">Lv2-初中</option> <option value="3">Lv3-高中</option> <option value="4">Lv4-本科</option> <option value="5">Lv5-硕士</option> <option value="6">Lv6-博士</option> <option value="7">Lv7-博士后</option> </select> </div> </div> <div class="form-group"> <label for="intelligence" class="col-sm-2 control-label">智力</label> <div class="col-sm-10"> <input type="text" class="form-control" name="intelligence" id="intelligence" value='{{ cur_user_attr.intelligence }}'> </div> </div> <div class="form-group"> <label for="memory" class="col-sm-2 control-label">记忆力</label> <div class="col-sm-10"> <input type="text" class="form-control" name="memory" id="memory" value='{{ cur_user_attr.memory }}'> </div> </div> <div class="form-group"> <label for="diligence" class="col-sm-2 control-label">勤奋力</label> <div class="col-sm-10"> <input type="text" class="form-control" name="diligence" id="diligence" value='{{ cur_user_attr.diligence }}'> </div> </div> <div class="form-group"> <label for="physicalFitness" class="col-sm-2 control-label">体能</label> <div class="col-sm-10"> <input type="text" class="form-control" name="physicalFitness" id="physicalFitness" value='{{ cur_user_attr.physical_fitness }}'> </div> </div> <div class="form-group"> <label for="totalPoints" class="col-sm-2 control-label">总积分</label> <div class="col-sm-10"> <input type="text" class="form-control" name="totalPoints" id="totalPoints" value='{{ cur_user_attr.total_points }}' readonly="readonly"> </div> </div> <div class="form-group"> <label for="otherSubjects" class="col-sm-2 control-label">学科属性</label> <div class="col-sm-10"> <textarea name="otherSubjects" id="otherSubjects" class="form-control" rows="4">{{ cur_user_attr.other_subjects }}</textarea> </div> </div> <div class="form-group"> <label for="notes" class="col-sm-2 control-label">备注提醒</label> <div class="col-sm-10"> <textarea name="notes" id="notes" class="form-control" rows="4">{{ cur_user_attr.notes }}</textarea> </div> </div> {% endif %} <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <a href="javascript:updateUserInfo()" class="btn btn-default btn-lg btn-block btn-a">提交保存</a> </div> </div> </form> {% else %} <strong>查无记录</strong> {% endif %} </div> <script type="text/javascript"> // html加载的时候执行该函数 $(document).ready(function () { {# 学生用户属性值#} var cur_user_attr = '{{ cur_user_attr }}'; // 用户属性不为空时 if (cur_user_attr) { // 学习级别,当前选中值 var study_level = '{{ cur_user_attr.study_level }}'; // 创建list数据,对应级别值 var level_list = [1, 2, 3, 4, 5, 6, 7,]; for (var index in level_list) { var key = level_list[index]; {#alert("key:" + key);#} if (study_level == key) { {#方法1、设置value为pxx的项选中#} $("select[name='studyLevel']").val(key); } } } // 创建json格式数据 {#var levelJson = [{level: 1, desc: "Lv1-小学"},#} {# {level: 2, desc: "Lv2-初中"},#} {# {level: 3, desc: "Lv3-高中"},#} {# {level: 4, desc: "Lv4-本科"},#} {# {level: 5, desc: "Lv5-硕士"},#} {# {level: 6, desc: "Lv6-博士"},#} {# {level: 7, desc: "Lv7-博士后"},#} {#];#} {#for (var index in levelJson) {#} {# var key = levelJson[index].level;#} {#var value = levelJson[index].desc;#} {#if (study_level == key) {#} {#alert("study_level:" + study_level);#} {#方法1、设置value为pxx的项选中#} {#$("select[name='studyLevel']").val(key);#} {#方法2、设置text为pxx的项选中#} {#$("select[name='studyLevel']").find("option[text=key]").attr("selected", true);#} {# }#} {#/}#} }); </script>
第二步:运行测试-用户管理功能
1,登录用户后,点击查看用户信息页面
2,点击查看积分明细页面
3,点击修改用户页面
-------------------------------------------------end -------------------------------------------------