写在前面
- 接了个搭建网站的活,是个长期工程,后续会慢慢更新
- 在chatgpt的帮助下,用一天时间完成了用户管理功能
功能
- 用户管理CRUD
- 基于用户角色的权限划分
- 未登录拦截、会话保持
- 用户信息加密保存
技术栈
- django负责后端处理和转发页面
- bootstrap美化界面
效果展示
- 登录界面
- 用户管理界面(只有root用户能进入)
核心代码
用户管理app
import hashlib
from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt
from manage import models
from .forms import SelectAdminForm
def user_list(request):
user_set = models.User.objects.all()
return render(request, 'user_list.html', {"user_set": user_set})
@csrf_exempt
def user_add(request):
if request.method == 'GET':
select_form = SelectAdminForm()
return render(request, 'user_add.html', {'select_form': select_form})
username = request.POST.get("username")
password = request.POST.get("password")
is_admin = request.POST.get("is_admin")
models.User.objects.create(username=username, password=password, is_admin=is_admin)
return redirect('../')
@csrf_exempt
def user_edit(request):
user_id = request.GET.get('user_id')
row_object = models.User.objects.filter(id=user_id).first()
select_form = SelectAdminForm()
if request.method == 'GET':
return render(request, 'user_edit.html', {"form": row_object, "select_form": select_form})
username = request.POST.get("username")
password = request.POST.get("password")
is_admin = request.POST.get("is_admin")
models.User.objects.filter(id=user_id).update(username=username, password=password, is_admin=is_admin)
return redirect('../')
def user_delete(request):
user_id = request.GET.get('user_id')
models.User.objects.filter(id=user_id).delete()
return redirect('../')
from django.db import models
class User(models.Model):
username = models.CharField(max_length=50)
password = models.CharField(max_length=100)
ADMIN_VALUE = (('是', '是'), ('否', '否'))
is_admin = models.CharField(max_length=10, choices=ADMIN_VALUE)
def __str__(self):
return self.username
def is_valid(self):
if len(self.password) > 1:
return True
class Administrator(models.Model):
username = models.CharField(max_length=50)
password = models.CharField(max_length=50)
def __str__(self):
return self.username
{% extends 'base.html' %}
{% block title %}
用户管理
{% endblock %}
{% block content %}
<div class="container">
<div style="margin-bottom: 10px" class="clearfix">
<a class="btn btn-success" href="/manage/add">
<span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>
新建用户
</a>
<div style="float: right;width: 300px">
<form method="get">
<div class="input-group">
<input type="text" name="q" class="form-control" placeholder="请输入查找用户名称"
value="{{ search_data }}">
<span class="input-group-btn">
<button class="btn btn-default" type="submit">
<span class="glyphicon glyphicon-search" aria-hidden="true"></span>
</button>
</span>
</div>
</form>
</div>
</div>
<div class="bs-example" data-example-id="panel-without-body-with-table">
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading">
<span class="glyphicon glyphicon-th-list" aria-hidden="true"></span>
用户列表
</div>
<!-- Table -->
<table class="table table-bordered">
<thead>
<tr>
<th>序号</th>
<th>用户名</th>
<th>密码</th>
<th>是否管理员</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for obj in user_set %}
<tr>
<th scope="row">{{ obj.id }}</th>
<td>{{ obj.username }}</td>
<td>{{ obj.password }}</td>
<td>{{ obj.is_admin }}</td>
<td>
<a class="btn btn-primary btn-xs" href="/manage/edit/?user_id={{ obj.id }}">编辑</a>
<a class="btn btn-danger btn-xs" href="/manage/delete/?user_id={{ obj.id }}">删除</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
<ul class="pagination">
{{ page_string }}
</ul>
</div>
{% endblock %}
登录app
from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt
from manage import models
from .forms import LoginForm
import hashlib
@csrf_exempt
def user_login(request):
if request.session.get('is_login', None):
return redirect('../manage')
if request.method == 'GET':
login_form = LoginForm()
return render(request, 'user_login.html', locals())
else:
login_form = LoginForm(request.POST)
if login_form.is_valid():
username = login_form.cleaned_data["username"]
password = login_form.cleaned_data["password"]
try:
user = models.User.objects.get(username=username)
if user.password == password:
request.session['is_login'] = True
request.session['user_id'] = user.id
request.session['user_name'] = user.username
if user.username == "root":
return redirect('../manage')
return redirect('../manage')
else:
message = "密码不正确!"
except:
message = "用户不存在"
return render(request, 'user_login.html', locals())
@csrf_exempt
def user_logout(request):
if request.session.get('is_login', None):
request.session.flush()
return redirect("../../login")
@csrf_exempt
def user_register(request):
login_form = LoginForm()
message = "请联系管理员进行用户注册!"
return render(request, 'user_login.html', locals())
- user_login.html,不知道为啥同一个项目下的不同app只能使用同一个base.html,django貌似只会扫描第一个app目录下的templates下的base.html
{% extends 'base.html' %}
{% block title %}登录{% endblock %}
{% block content %}
<div class="container">
<div class="col-md-4 col-md-offset-4">
<form class='form-login' action="/login/" method="post">
{% if message %}
<div class="alert alert-warning">{{ message }}</div>
{% endif %}
{% csrf_token %}
<h2 class="text-center">欢迎登录</h2>
<div class="form-group">
{{ login_form.username}}
</div>
<div class="form-group">
{{ login_form.password }}
</div>
<button type="reset" class="btn btn-default pull-left">重置</button>
<button type="submit" class="btn btn-primary pull-right">登录</button>
</form>
</div>
</div> <!-- /container -->
{% endblock %}
middleware app
- LoginMiddleWare.py,用来做未登录拦截
from django.shortcuts import HttpResponseRedirect
from django.contrib import messages
from django.shortcuts import render, redirect
from login.forms import LoginForm
try:
from django.utils.deprecation import MiddlewareMixin # Django 1.10.x
except ImportError:
MiddlewareMixin = object # Django 1.4.x - Django 1.9.x
# 不需要登录用户就能能访问的地址列表
login_list = ['/login/', '/login/register/']
#只有root用户才能访问的地址列表
#manage_list = ['/manage/', '/manage/add/', '/manage/edit', '/manage/delete']
manage_list = []
class SimpleMiddleware(MiddlewareMixin):
def process_request(self, request):
if request.path not in login_list:
print (request.path)
username = request.session.get('user_name', None)
if username is not None:
if username!="root" and request.path in manage_list:
login_form = LoginForm()
message = "请用超级管理员账号登录后台!"
return render(request, 'user_login.html', locals())
pass
else:
login_form = LoginForm()
message = "请先登录用户!"
return render(request, 'user_login.html', locals())
写在后面
- 这种纯CRUD的活,完全可以模式化,未来肯定会被机器取代
- 就我目前使用chatgpt的体验而言,它更多是帮我写一个模板,很多细节方面的实现还需要我自己去调整,而且它甚至会给我一些有错误的代码,卡了我挺长时间...
- 它确实很强了,比我自己去必应找代码更方面更快捷,免去一些无关的信息筛选,提高了我不少效率,但目前感觉它还无法完全替代必应,毕竟互联网上有海量的技术博客、经验分享,就比如安装django有很多踩坑,必应的话会有很多前人的坑点总结,chatgpt的优势是提供优质经过筛选的信息,而不是信息的规模量