Django-员工操作
Published in:2020-08-28 |

Django实现用户登陆,注册,以及session会话强制登陆,以及对员工的信息的增加,删除,修改操作,中间件,上传头像,验证码 ,分页显示

新增模糊查询,使用 Jquery-Ajax

新增登陆时只更新部分内容,使用Ajax控制

view视图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# 注册页面
def regist(request):
return render(request, "work/regist.html")

# 添加员工页面
def addEmp(request):
return render(request, "work/addEmp.html")

# 修改员工页面
def updateEmp(request):
# 填写获取的该员工信息
id = request.GET.get('id')
staff = Staff.objects.get(pk=id)
return render(request, "work/updateEmp.html", {"staff": staff})

# 登陆逻辑
def login_logic(request):
if request.method == "GET":
username = request.GET.get("name")
userpwd = request.GET.get("pwd")
else:
username = request.POST.get("name")
userpwd = request.POST.get("pwd")
res = User.objects.filter(username=username, userpwd=userpwd)
if res:
request.session['is_login'] = True # 登陆正确设置及session会话
return HttpResponse('ok')
return HttpResponse('用户名或密码错误')

# # 模糊查询
def query(request):
staff = request.GET.get("query")
res = Staff.objects.filter(name__icontains=staff)
print(res)
def mydefault(u):
if isinstance(u,Staff):
return {'name':u.name,'salary':float(u.salary),'age':u.age}

return JsonResponse({'staff':list(res)},safe=False,json_dumps_params={'default':mydefault})

# 随机码
def getCaptacha(request):
image = ImageCaptcha()
code = random.sample(string.ascii_lowercase + string.ascii_uppercase + string.digits, 4)
random_code = ''.join(code)
request.session['code'] = random_code
data = image.generate(random_code)
return HttpResponse(data, "image/png")

# 注册逻辑
def regist_logic(request):
username = request.POST.get("username")
name = request.POST.get("name")
userpwd = request.POST.get("pwd")
sex = request.POST.get("sex")
# 获取输入的验证码
captcha = request.POST.get('captcha')
code = request.session.get('code')
if code.lower() == captcha.lower():
res = User.objects.filter(username=username) # 获取数据库是否拥有用户名
if res:
return HttpResponse("用户已存在")
with transaction.atomic():
User.objects.create(username=username, name=name, userpwd=userpwd, sex=sex)
return redirect("work:login")
else:
return HttpResponse('注册失败')

# 添加员工逻辑
def addEmp_logic(request):
# # 判断是否存在session,不存在强制返回登陆界面
# res = request.session.get('is_login')
# if res:
# return redirect("work:emplist_logic") # 存在session,返回员工页面
name = request.POST.get('name')
salary = request.POST.get('salary')
age = request.POST.get('age')
# 获取上传的头像
pic = request.FILES.get('head_pic')
ext = os.path.splitext(pic.name)[1] # 获取后缀
head_pic = str(uuid.uuid4()) + ext # 拼接后缀名
pic.name = head_pic
with transaction.atomic():
Staff.objects.create(name=name, salary=salary, age=age, pic=pic)
return redirect("work:emplist_logic")

# 修改数据逻辑
def updateEmp_logic(request):
# 根据修改页面的该员工的id
id = request.GET.get('id')
print(id)
staff = Staff.objects.get(pk=id)
# 获取到提交的修改数据
name = request.POST.get('name')
salary = request.POST.get('salary')
age = request.POST.get('age')
# 修改图片
pic = request.FILES.get('head_pic')
ext = os.path.splitext(pic.name)[1] # 获取后缀
head_pic = str(uuid.uuid4()) + ext # 拼接后缀名
pic.name = head_pic
# 进行员工的信息修改
with transaction.atomic():
staff.name = name
staff.salary = salary
staff.age = age
staff.pic = pic
staff.save()
return redirect("work:emplist")

# 删除员工
def delete_logic(request):
with transaction.atomic():
id = request.GET.get('id')
staff = Staff.objects.filter(pk=id)
staff.delete()
return redirect('work:emplist')

# 主页逻辑
def emplist_logic(request):
# 分页需要导包Paginator
num = request.GET.get('num', 1)
paginator = Paginator(Staff.objects.all(), per_page=3) # 每页显示3条数据
page = paginator.page(num) # 构建页面对象

return render(request, 'work/emplist.html', {"page": page})

emplistHtml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
{% load static %}
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>emplist</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="{% static 'work/css/style.css' %}"/>
<script src="{% static 'work/js/jquery-1.11.1.min.js' %}"></script>
<script>
function f() {
var table = document.getElementById('t1');
var query = document.getElementById('s1');
$.ajax({
type: 'GET',
url: '{% url 'work:query' %}',
data: "query=" + query.value,
success: function (c) {
c = c['staff'];
console.log(c);
var str = '<tr><td>姓名</td><td>薪水</td><td>年龄</td></tr>';
for (var i = 0; i < c.length;i++) {
str += "<tr>";
str += "<td>";
str += c[i]['name'];
str += "</td>";
str += "<td>";
str += c[i]['salary'];
str += "</td>";
str += "<td>";
str += c[i]['age'];
str += "</td>";
str += "</tr>";
}
table.innerHTML = str
}
})
}

</script>
</head>
<body>
<div id="wrap">
<div id="top_content">
<div id="header">
<div id="rightheader">
<p>
2009/11/20
<br/>
</p>
</div>
<div id="topheader">
<h1 id="title">
<a href="#">main</a>
</h1>
</div>
<div id="navigation">
</div>
</div>
<div id="content">
<p id="whereami">
</p>
<h1>
Welcome!
</h1>
<div>
<input type="text" id="s1">
<input type="button" value="搜索" onclick="f()">
</div>
<table class="table" id="t1">
<tr class="table_header">
<td>
ID
</td>
<td>
Name
</td>
<td>
Salary
</td>
<td>
Age
</td>
<td>
head_pic
</td>
<td>
Operation
</td>
</tr>
{% for i in page.object_list %}
{% if forloop.counter|divisibleby:2 %}
<tr class="row1" style="background-color: #ffffff">
<td>
{{ forloop.counter }}
</td>
<td>
{{ i.name }}
</td>
<td>
{{ i.salary }}
</td>
<td>
{{ i.age }}
</td>
<td>
<img src="{% static i.pic.url %}" alt="图片加载失败" height="70px">
</td>
<td>
<a href="{% url "work:delete_logic" %}?id={{ i.id }}">delete emp</a>&nbsp;<a
href="{% url "work:updateemp" %}?id={{ i.id }}">update emp</a>
</td>

</tr>
{% else %}
<tr class="row2" style="background-color: #eeeeee">
<td>
{{ forloop.counter }}
</td>
<td>
{{ i.name }}
</td>
<td>
{{ i.salary }}
</td>
<td>
{{ i.age }}
</td>
<td>
<img src="{% static i.pic.url %}" alt="图片加载失败" height="70px">
</td>
<td>
<a href="{% url "work:delete_logic" %}?id={{ i.id }}">delete emp</a>&nbsp;<a
href="{% url "work:updateemp" %}?id={{ i.id }}">update emp</a>
</td>

</tr>
{% endif %}
{% endfor %}
</table>
{% if page.has_previous %}
<a href="{% url 'work:emplist_logic' %}?num={{ page.previous_page_number }}"> 上一页</a>
{% endif %}

{% for foo in page.paginator.page_range %}
<a href="{% url 'work:emplist_logic' %}?num={{ foo }}">
{% if foo == page.number %}
<span class="b">{{ foo }}</span>
{% else %}
<span class="a">{{ foo }}</span>
{% endif %}
</a>
{% endfor %}
{% if page.has_next %}
<a href="{% url 'work:emplist_logic' %}?num={{ page.next_page_number }}"> 下一页</a>
{% endif %}
{% if not page.paginator.num_pages == page.number %}
<a href="{% url 'work:emplist_logic' %}?num={{ page.paginator.num_pages }}">尾页</a>
{% endif %}

<form action="{% url 'work:emplist_logic' %}" method="get">
输入页号<input type="text" name="num">
<input type="submit" value="跳转">
<p>
<input type="button" class="button" value="Add Employee"
onclick="location='{% url "work:addemp" %}'"/>
</p>

</form>
</div>
</div>
<div id="footer">
<div id="footer_bg">
ABC@126.com
</div>
</div>
</div>
</body>
</html>

login.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
{% load static %}
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>login</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css"
href="/static/work/css/style.css"/>
<script>
function f1() {
var name = document.getElementById("name").value;
var pwd = document.getElementById("pwd").value;
var s1 = document.getElementById("s1");
var xml = new XMLHttpRequest();
xml.open('POST', '{% url 'work:login_logic' %}', true);
xml.setRequestHeader("Content-type", 'application/x-www-form-urlencoded');
xml.send('name=' + name + '&pwd=' + pwd + '&csrfmiddlewaretoken={{ csrf_token }}');
{#回调函数#}
xml.onreadystatechange = function () {
if (xml.readyState == 4 && xml.status == 200) {
var text = xml.responseText;
console.log(text);
if (text == 'ok') {
{#s1.innerHTML = text;#}
location.href ="{% url 'work:emplist_logic' %}"
} else {
s1.innerHTML = text;
document.getElementById("pwd").value = '';
}
}
}
}
</script>
</head>

<body>
<div id="wrap">
<div id="top_content">
<div id="header">
<div id="rightheader">
<p>
2009/11/20
<br/>
</p>
</div>
<div id="topheader">
<h1 id="title">
<a href="#">main</a>
</h1>
</div>
<div id="navigation">
</div>
</div>
<div id="content">
<p id="whereami">
</p>
<h1>
login
</h1>
<form action="{% url "work:login_logic" %}" method="post" enctype="application/x-www-form-urlencoded">
{% csrf_token %}
<table cellpadding="0" cellspacing="0" border="0"
class="form_table">
<tr>
<td valign="middle" align="right">
username:
</td>
<td valign="middle" align="left">
<input type="text" class="inputgri" name="name" id="name"/>
<span id="s1"></span>
</td>
</tr>
<tr>
<td valign="middle" align="right">
password:
</td>
<td valign="middle" align="left">
<input type="password" class="inputgri" name="pwd" id="pwd"/>
</td>
</tr>
</table>
<p>
<input type="button" onclick="f1()" class="button" value="Submit &raquo;"/>
</p>
</form>
</div>
</div>
<div id="footer">
<div id="footer_bg">
ABC@126.com
</div>
</div>
</div>
</body>
</html>
Prev:
Django-ems重构
Next:
Django-员工操作