You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

95 lines
3.2 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

from django.shortcuts import render, redirect
from app01 import models
from app01.utils.pagination import Pagination
from app01.utils.form import UserModelForm, PrettyModelForm, PrettyEditModelForm
def user_list(request):
""" 用户管理 """
data_dict = {}
search_data = request.GET.get('q', "")
if search_data:
data_dict["name__contains"] = search_data
queryset = models.UserInfo.objects.filter(**data_dict)
page_object = Pagination(request, queryset, page_size=6)
context = {
"queryset": page_object.page_queryset,
"page_string": page_object.html(),
'search_data': search_data,
}
return render(request, 'user_list.html', context)
def user_add(request):
""" 添加用户(原始方式) """
if request.method == "GET":
context = {
'gender_choices': models.UserInfo.gender_choices,
"depart_list": models.Department.objects.all()
}
return render(request, 'user_add.html', context)
# 获取用户提交的数据
user = request.POST.get('user')
pwd = request.POST.get('pwd')
age = request.POST.get('age')
account = request.POST.get('ac')
ctime = request.POST.get('ctime')
gender = request.POST.get('gd')
depart_id = request.POST.get('dp')
# 添加到数据库中
models.UserInfo.objects.create(name=user, password=pwd, age=age,
account=account, create_time=ctime,
gender=gender, depart_id=depart_id)
# 返回到用户列表页面
return redirect("/user/list/")
def user_model_form_add(request):
""" 添加用户ModelForm版本"""
if request.method == "GET":
form = UserModelForm()
return render(request, 'user_model_form_add.html', {"form": form})
# 用户POST提交数据数据校验。
form = UserModelForm(data=request.POST)
if form.is_valid():
# 如果数据合法,保存到数据库
# {'name': '123', 'password': '123', 'age': 11, 'account': Decimal('0'), 'create_time': datetime.datetime(2011, 11, 11, 0, 0, tzinfo=<UTC>), 'gender': 1, 'depart': <Department: IT运维部门>}
# print(form.cleaned_data)
# models.UserInfo.objects.create(..)
form.save()
return redirect('/user/list/')
# 校验失败(在页面上显示错误信息)
return render(request, 'user_model_form_add.html', {"form": form})
def user_edit(request, nid):
""" 编辑用户 """
row_object = models.UserInfo.objects.filter(id=nid).first()
if request.method == "GET":
# 根据ID去数据库获取要编辑的那一行数据对象
form = UserModelForm(instance=row_object)
return render(request, 'user_edit.html', {'form': form})
form = UserModelForm(data=request.POST, instance=row_object)
if form.is_valid():
# 默认保存的是用户输入的所有数据,如果想要再用户输入以外增加一点值
# form.instance.字段名 = 值
form.save()
return redirect('/user/list/')
return render(request, 'user_edit.html', {"form": form})
def user_delete(request, nid):
models.UserInfo.objects.filter(id=nid).delete()
return redirect('/user/list/')