【Django Series - 03】使用者管理模組:建立使用者、登入、退出
阿新 • • 發佈:2018-10-31
Django Series(Django2.1.2 + Anaconda3)
(一)安裝並配置 Django 環境 ||| 基於 Django 進行 Web 開發
(四)資料的增刪改:使用者提交資料,驗證資料的有效性並傳輸至後臺(jQuery.post、jQuery.getJSON)
(五)基於 "xlsxwriter + BytesIO"(Python3)生成 Excel 報表 ||| Python2 StringIO.StringIO()
說明:本系列教程根據最近實踐過程進行整理、總結和分享。由於時間和精力有限,發表時內容分析部分可能不是很完整
更新日誌:
20181019:發表第一版,主要以程式碼分享為主;知識點分析較為粗略。
知識點分析:
實現程式碼:
models.py
# -*- coding: utf-8 -*- from django.db import models from django.contrib.auth.models import User class BRsystemUser(models.Model): Users = models.OneToOneField(User, on_delete = models.CASCADE) UserName = models.CharField(max_length = 20, verbose_name = u'使用者ID') UserPWD = models.CharField(max_length = 20, verbose_name = u'使用者密碼') RoleTypeID = models.CharField(max_length = 10, verbose_name = u'使用者型別ID') #使用者型別:"admin"為管理員, "general"為普通員工 NickName = models.CharField(max_length = 20, verbose_name = u'暱稱') #使用者真正名字 RegisterTime = models.DateTimeField(auto_now_add = True, verbose_name = u'註冊時間') MobilePhone = models.CharField(max_length = 11, verbose_name = u'手機號碼', null = True) #電話號碼 Note = models.CharField(default = 'None', max_length = 100, verbose_name = u'備註',null = True) def __str__(self): return self.Users.username + ' ' + self.RoleTypeID
urls.py
from django.urls import include, path, re_path
from app_ManageSystem import views
app_name = 'app_ManageSystem'
urlpatterns = [
path(r'Login', views.Login, name='Login'),
path(r'Logout', views.Logout, name='Logout'),
]
views.py
### 系統登入介面 @csrf_exempt def Login(request): context = {} if request.POST: UserName = request.POST.get('form_UserName') UserPWD = request.POST.get('form_UserPWD') print(UserName, UserName) user = auth.authenticate(username = UserName, password = UserPWD) if user is not None: print("{} login successful".format(UserName)) if user.is_active: auth.login(request, user) sys_user = BRsystemUser.objects.get(Users = user) request.session["UserName"] = sys_user.UserName request.session["UserPWD"] = sys_user.UserPWD request.session["RoleTypeID"] = sys_user.RoleTypeID request.session["NickName"] = sys_user.NickName request.session["MobilePhone"] = sys_user.MobilePhone request.session["Note"] = sys_user.Note request.session["log_file_path"] = os.path.join("report", "log", sys_user.UserName + ".txt") hcq_write(request.session.get('log_file_path'), True, False, "[{}({})] 成功登入系統".format( sys_user.UserName, sys_user.RoleTypeID)) return HttpResponseRedirect('/') # return render(request, 'Login.html', context) else: print("{} login failure: not_active".format(UserName)) else: ## user is not exist or pwd is error print("{} login failure: user is not exist or pwd is error".format(UserName)) return render(request, 'Login.html', context) # 登出 @csrf_exempt def Logout(request): hcq_write(request.session.get('log_file_path'), True, False, "[{}({})] 成功退出系統".format( request.session.get('UserName'), request.session.get('RoleTypeID'))) auth.logout(request) return HttpResponseRedirect('/')
Login.html
<body>
<table width="100%">
<!-- 頂部部分 -->
<tr height="41"><td colspan="2" background="{% static 'images/login_top_bg.gif' %}"> </td></tr>
<!-- 主體部分 -->
<tr style="background:url({% static 'images/login_bg.jpg' %}) repeat-x;" height="532">
<!-- 主體右部分 -->
<td id="right_cont">
<table height="100%">
<tr height="30%"><td colspan="3"> </td></tr>
<tr>
<td width="30%" rowspan="5"> </td>
<td valign="top" id="form">
<form action="" method="post">
{% csrf_token %}
<table valign="top" width="50%">
<tr>
<td colspan="2">
<h4 style="letter-spacing:1px; font-size:16px; font-weight: bold;">xxxx管理系統</h4>
</td>
</tr>
<tr>
<td>賬號:</td>
<td>
<input type="text" id="form_UserName" name="form_UserName" value="" placeholder="請輸入使用者名稱...">
</td>
</tr>
<tr>
<td>密碼:</td>
<td>
<input type="password" id="form_UserPWD" name="form_UserPWD" value="" placeholder="請輸入密碼...">
</td>
</tr>
<!-- <tr>
<td>驗證碼:</td>
<td>
<input type="text" name="" value="" style="width:80px;"/>
</td>
</tr> -->
<tr class="bt" align="center">
<td>
<input type="submit" value="登入" />
</td>
<td>
<input type="reset" value="重填" />
</td>
</tr>
</table>
</form>
</td>
<td rowspan="5"> </td>
</tr>
<tr><td colspan="3"> </td></tr>
</table>
</td>
</tr>
<tr id="login_bot"><td colspan="2"><p>Copyright © 2018 </p></td></tr>
</table>
</body>
base.html
<body>
<div class="container-fluid">
<table cellpadding="0" width="100%" height="64" background="{% static 'images/top_top_bg.gif' %}">
<tr valign="top">
<td width="50%">
<a href="/"> <!-- 返回主頁 -->
<img style="border:none" src="{% static 'images/logo3.png' %}" />
</a>
</td>
<td width="30%" style="padding-top:13px;font:15px Arial,SimSun,sans-serif;color:#FFF">
{% if UserName %}
{% ifequal RoleTypeID 'admin' %}
尊敬的 <b>{{ NickName }}</b>(管理員) 您好,感謝登陸使用!
{% else %}
尊敬的 <b>{{ NickName }}</b> 您好,感謝登陸使用!
{% endifequal %}
{% else %}
您好,請先登入!
{% endif %}
</td>
<td style="padding-top:10px;padding-right:10px;" align="right">
<a href="\"><img style="border:none" src="{% static 'images/index.gif' %}" /></a>
<a href="{% url 'app_ManageSystem:Logout' %}"><img style="border:none" src="{% static 'images/out.gif' %}" /></a>
</td>
</tr>
</table>
</div>
</body>
建立使用者:
# -*- coding: utf-8 -*-
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'BR_Pro_Manage_System.settings')
django.setup()
from app_ManageSystem.models import *
def Add_Users(UserName, UserPWD, RoleTypeID, NickName):
try:
if not User.objects.filter(username = UserName, password = UserPWD).exists():
NewUser = User.objects.create_user(username = UserName, password = UserPWD)
NewUser.save()
if not BRsystemUser.objects.filter(Users = NewUser, UserName = UserName).exists():
new_myuser = BRsystemUser.objects.get_or_create(Users = NewUser, UserName = UserName, UserPWD = UserPWD, RoleTypeID = RoleTypeID, NickName = NickName)[0]
new_myuser.save()
print("[{}] saved".format(UserName))
except Exception as e:
print("[error] Add_Users: {}".format(e))
### main
def population():
# # Add_Users(UserName, UserPWD, RoleTypeID, NickName)
Add_Users("hcq", "123", "general", "houchaoqun")
Add_Users("jackan", "123", "admin", "kangjie")
### main program
if __name__ == '__main__':
population()