原始方式理思路:不会采用(本质)【麻烦】
- 用户提交数据没有校验。
- 错误,页面上应该有错误提示。
- 页面上,每一个字段都需要我们重新写一遍。 [OK]
- 关联的数据,手动去获取并展示循环展示在页面。 [OK]
所以我们一般使用Form和ModelForm来实现
user_list.html
{% extends 'layout.html' %}
{% block content %}
<div class="container">
<div style="margin-bottom: 10px">
<a class="btn btn-success" href="/user/add/">
<span class="glyphicon glyphicon-plus-sign" aria-hidden="true">span>
新建用户
a>
<a class="btn btn-success" href="/user/model/form/add/">
<span class="glyphicon glyphicon-plus-sign" aria-hidden="true">span>
新建用户ModelForm
a>
div>
<div class="panel panel-default">
<div class="panel-heading">
<span class="glyphicon glyphicon-th-list" aria-hidden="true">span>
用户列表
div>
<table class="table table-bordered">
<thead>
<tr>
<th>IDth>
<th>姓名th>
<th>密码th>
<th>年龄th>
<th>余额th>
<th>入职时间th>
<th>性别th>
<th>所属部门th>
<th>操作th>
tr>
thead>
<tbody>
{% for obj in queryset %}
<tr>
<th>{{ obj.id }}th>
<td>{{ obj.name }}td>
<td>{{ obj.password }}td>
<td>{{ obj.age }}td>
<td>{{ obj.account }}td>
<td>{{ obj.create_time|date:"Y-m-d" }}td>
<td>{{ obj.get_gender_display }}td>
<td>{{ obj.depart.title }}td>
<td>
<a class="btn btn-primary btn-xs" href="/user/{{ obj.id }}/edit/">编辑a>
<a class="btn btn-danger btn-xs" href="/user/{{ obj.id }}/delete/">删除a>
td>
tr>
{% endfor %}
tbody>
table>
div>
<ul class="pagination">
{{ page_string }}
ul>
div>
{% endblock %}
user_add.html
{% extends 'layout.html' %}
{% block content %}
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"> 新建用户 h3>
div>
<div class="panel-body">
<form method="post">
{% csrf_token %}
<div class="form-group">
<label>姓名label>
<input type="text" class="form-control" placeholder="姓名" name="user" />
div>
<div class="form-group">
<label>密码label>
<input type="text" class="form-control" placeholder="密码" name="pwd"/>
div>
<div class="form-group">
<label>年龄label>
<input type="text" class="form-control" placeholder="年龄" name="age"/>
div>
<div class="form-group">
<label>余额label>
<input type="text" class="form-control" placeholder="余额" name="ac"/>
div>
<div class="form-group">
<label>入职时间label>
<input type="text" class="form-control" placeholder="入职时间" name="ctime"/>
div>
<div class="form-group">
<label>性别label>
<select class="form-control" name="gd">
{% for item in gender_choices %}
<option value="{{ item.0 }}">{{ item.1 }}option>
{% endfor %}
select>
div>
<div class="form-group">
<label>部门label>
<select class="form-control" name="dp">
{% for item in depart_list %}
<option value="{{ item.id }}">{{ item.title }}option>
{% endfor %}
select>
div>
<button type="submit" class="btn btn-primary">提 交button>
form>
div>
div>
div>
{% endblock %}
user_model_form_add.html
{% extends 'layout.html' %}
{% block content %}
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"> 新建用户 h3>
div>
<div class="panel-body">
<form method="post" novalidate>
{% csrf_token %}
{% for field in form %}
<div class="form-group">
<label>{{ field.label }}label>
{{ field }}
<span style="color: red;">{{ field.errors.0 }}span>
div>
{% endfor %}
<button type="submit" class="btn btn-primary">提 交button>
form>
div>
div>
div>
{% endblock %}
user_edit.html
{% extends 'layout.html' %}
{% block content %}
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"> 编辑用户 h3>
div>
<div class="panel-body">
<form method="post" novalidate>
{% csrf_token %}
{% for field in form %}
<div class="form-group">
<label>{{ field.label }}label>
{{ field }}
<span style="color: red;">{{ field.errors.0 }}span>
div>
{% endfor %}
<button type="submit" class="btn btn-primary">提 交button>
form>
div>
div>
div>
{% endblock %}
urls.py
from django.contrib import admin
from django.urls import path
from app01 import views
urlpatterns = [
#path('admin/', admin.site.urls),
# 部门管理
path('depart/list/', views.depart_list),
path('depart/add/', views.depart_add),
path('depart/delete/', views.depart_delete),
path('depart//edit/' , views.depart_edit),
# 用户管理
path('user/list/', views.user_list),
path('user/add/', views.user_add),
path('user/model/form/add/', views.user_model_form_add),
path('user//edit/' , views.user_edit),
path('user//delete/' , views.user_delete),
]
views.py
def user_list(request):
""" 用户管理 """
# 获取所有用户列表 [obj,obj,obj]
queryset = models.UserInfo.objects.all()
"""
# 用Python的语法获取数据
for obj in queryset:
print(obj.id, obj.name, obj.account, obj.create_time.strftime("%Y-%m-%d"), obj.gender, obj.get_gender_display(), obj.depart_id, obj.depart.title)
# print(obj.name, obj.depart_id)
# obj.depart_id # 获取数据库中存储的那个字段值
# obj.depart.title # 根据id自动去关联的表中获取哪一行数据depart对象。
"""
return render(request, 'user_list.html', {"queryset": queryset})
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/")
# ################################# ModelForm 示例 #################################
from django import forms
class UserModelForm(forms.ModelForm):
name = forms.CharField(min_length=3, label="用户名")
class Meta:
model = models.UserInfo
fields = ["name", "password", "age", 'account', 'create_time', "gender", "depart"]
# widgets = {
# "name": forms.TextInput(attrs={"class": "form-control"}),
# "password": forms.PasswordInput(attrs={"class": "form-control"}),
# "age": forms.TextInput(attrs={"class": "form-control"}),
# }
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# 循环找到所有的插件,添加了class="form-control"
for name, field in self.fields.items():
# if name == "password":
# continue
field.widget.attrs = {"class": "form-control", "placeholder": field.label}
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=), 'gender': 1, 'depart': }
# 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/')
访问: http://127.0.0.1:8000/user/list/
新建用户(Form)
新建用户(ModelForm)