管理员列表、增删改查
1. ModelForm和BootStrap
- ModelForm可以帮助我们生成HTML标签
class UserModelForm(forms.ModelForm):
class Meta:
model = models.UserInfo
fields = ["name", "password",]
form = UserModelForm()
- 定义插件
class UserModelForm(forms.ModelForm):
name = forms.CharField(
min_length=3,
label="姓名",
widget=forms.TextInput(attrs={'class':'form-control'})
)
class Meta:
model = models.UserInfo
fields = ["name", "gender", "age", "account_salary", "password", "depart", "create_date"]
- 重新定义init方法,批量设置
class UserModelForm(forms.ModelForm):
class Meta:
model = models.UserInfo
fields = ["name", "gender", "age"]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# 循环ModelForm中的所有字段,给每个字段的插件设置
for name, field in self.fields.items():
field.widget.attrs = {
'class': 'form-control',
'placeholder': field.label
}
class UserModelForm(forms.ModelForm):
class Meta:
model = models.UserInfo
fields = ["name", "gender", "age"]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# 循环ModelForm中的所有字段,给每个字段的插件设置
for name, field in self.fields.items():
# 字段中有属性,保留原有属性;没有属性,才增加
if field.widget.attrs:
field.widget.attrs["class"] = "form-control"
field.widget.attrs["placeholder"] = "请输入内容"
else:
field.widget.attrs = {
'class': 'form-control',
'placeholder': field.label
}
- 自定义类
class BootStrapModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# 循环ModelForm中的所有字段,给每个字段的插件设置
for name, field in self.fields.items():
# 字段中有属性,保留原有属性;没有属性,才增加
if field.widget.attrs:
field.widget.attrs["class"] = "form-control"
field.widget.attrs["placeholder"] = "请输入内容"
else:
field.widget.attrs = {
'class': 'form-control',
'placeholder': "请输入内容"
}
2. 管理员列表
""" 管理员列表 """
def admin_list(request):
# 搜索
data_dict = {}
search_data = request.GET.get('q', '')
if search_data:
data_dict["username__contains"] = search_data
# 根据搜索条件去数据库获取
queryset = models.Admin.objects.filter(**data_dict)
# 分页
page_object = Pagination(request, queryset)
context = {
'queryset': page_object.page_queryset,
'page_string': page_object.html(),
'search_data': search_data,
}
return render(request, 'admin_list.html', context)
<div class="container">
<div style="margin-bottom: 20px" class="clearfix">
<a href="/admin/add/" class="btn btn-success">
<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="panel panel-default">
<div class="panel-heading">
<span class="glyphicon glyphicon-list" aria-hidden="true"></span>
管理员账户列表
</div>
<table class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>用户名</th>
<th>密码</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for obj in queryset %}
{{ obj.id }}
{{ obj.username }}
********
编辑
删除
{% endfor %}
</tbody>
</table>
</div>
<div class="clearfix">
<ul class="pagination">
{{ page_string }}
</ul>
</div>
</div>
3. 添加管理员
class AdminModelForm(BootStrapModelForm):
confirm_password = forms.CharField(
label="确认密码",
widget=forms.PasswordInput()
)
class Meta:
model = models.Admin
fields = ["username", "password", "confirm_password"]
widgets = {
"password": forms.PasswordInput(render_value=True) # render_value=True 验证错误或不一致时,保留输入的值
}
# 对密码进行MD5加密
def clean_password(self):
pwd = self.cleaned_data.get("password")
return md5(pwd)
# 密码一致性判定
def clean_confirm_password(self):
print(self.cleaned_data)
password = self.cleaned_data.get("password")
confirm = md5(self.cleaned_data.get("confirm_password"))
if password != confirm:
raise ValidationError("密码不一致,请重新输入")
# 返回什么,此字段以后保存到数据库就是什么
return confirm
""" 添加管理员 """
def admin_add(request):
if request.method == "GET":
form = AdminModelForm()
context = {
'title': "新建管理员",
'form': form,
}
return render(request, 'change.html', context)
form = AdminModelForm(data=request.POST)
if form.is_valid():
form.save()
return redirect('/admin/list/')
return render(request, 'change.html', {'form': form, 'title': '新建管理员'})
from django.conf import settings
import hashlib
def md5(data_string):
obj = hashlib.md5(settings.SECRET_KEY.encode('utf-8'))
obj.update(data_string.encode('utf-8'))
return obj.hexdigest()
4. 编辑管理员
class AdminEditModelForm(BootStrapModelForm):
class Meta:
model = models.Admin
fields = ['username']
""" 编辑管理员 """
def admin_edit(request, nid):
# 对象 / None
row_object = models.Admin.objects.filter(id=nid).first()
# 如果不存在该ID,则返回错误页面(或重定向到管理员列表页面)
if not row_object:
return render(request, 'error.html', {'error_msg': '没有此管理员'})
# return redirect('/admin/list/')
if request.method == "GET":
form = AdminEditModelForm(instance=row_object)
context = {
'title': '编辑管理员',
'form': form,
}
return render(request, 'change.html', context)
form = AdminEditModelForm(data = request.POST, instance=row_object)
if form.is_valid():
form.save()
return redirect('/admin/list/')
return render(request, 'change.html', {'form': form, 'title': '编辑管理员'})
5. 删除管理员
简单处理
""" 删除管理员 """
def admin_delete(request, nid):
# 简单处理
models.Admin.objects.filter(id=nid).delete()
return redirect('/admin/list/')
6. 重置密码
class AdminResetModelForm(BootStrapModelForm):
confirm_password = forms.CharField(
label="确认密码",
widget=forms.PasswordInput()
)
class Meta:
model = models.Admin
fields = ['password', 'confirm_password']
widgets = {
"password": forms.PasswordInput(render_value=True) # render_value=True 验证错误或不一致时,保留输入的值
}
# 对密码进行MD5加密
def clean_password(self):
pwd = self.cleaned_data.get("password")
md5_pwd = md5(pwd)
# 去数据库校验当前密码和新输入的密码是否一致
exists = models.Admin.objects.filter(id=self.instance.pk, password=md5_pwd).exists()
if exists:
raise ValidationError("密码不能与原密码相同,请重新输入")
return md5_pwd
# 密码一致性判定
def clean_confirm_password(self):
print(self.cleaned_data)
password = self.cleaned_data.get("password")
confirm = md5(self.cleaned_data.get("confirm_password"))
if (password != confirm) and (password != None):
raise ValidationError("密码不一致,请重新输入")
# 返回什么,此字段以后保存到数据库就是什么
return confirm
""" 重置密码 """
def admin_reset(request, nid):
# 对象 / None
row_object = models.Admin.objects.filter(id=nid).first()
# 如果不存在该ID,则返回错误页面(或重定向到管理员列表页面)
if not row_object:
return redirect('/admin/list/')
title = "重置密码 - {}".format(row_object.username)
if request.method == "GET":
form = AdminResetModelForm()
context = {
'title': title,
'form': form
}
return render(request, 'change.html', context)
form = AdminResetModelForm(data = request.POST, instance=row_object)
if form.is_valid():
form.save()
return redirect('/admin/list/')
return render(request, 'change.html', {'form': form, 'title': title})