修改urls.py
path("user/add/", views.user_add),
添加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="name"/></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="money"/></div><div class="form-group"><label>入职时间</label><input type="text" class="form-control" placeholder="入职时间" name="time"/></div><div class="form-group"><label>性别</label>
{# 可以这么写,但是如果下拉选项过多的时候很费劲#}
{# <select class="form-control">#}
{# <option value="1">男</option>#}
{# <option value="2">女</option>#}
{# </select>#}<select class="form-control" name="gender">{% 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="dept">{% 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 %}
修改view.py
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)# 获取用户提交的数据name = request.POST.get("name")pwd = request.POST.get("pwd")age = request.POST.get("age")money = request.POST.get("money")time = request.POST.get("time")gender = request.POST.get("gender")dept = request.POST.get("dept")# 添加数据到数据库中models.UserInfo.objects.create(name=name, password=pwd, age=age, account=money, create_time=time, gender=gender, depart_id=dept)return redirect("/user/list/")
修改user_list.html
注意将user_list的路由替换
<a class="btn btn-success" href="/user/add"><span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>新建用户</a>
页面测试
缺点
- 用户提交数据没有校验
- 用户输错信息页面上没有错误提示
- html文件中每个字段都需要重写
- 关联的数据是手动获取并循环展示在页面