django之form功能

Django的Form主要具有一下几大功能:

  • 生成HTML标签
  • 验证用户数据(显示错误信息)
  • HTML Form提交保留上次提交数据
  • 初始化页面显示内容

1、form的创建:

示例:

class LoginForm(Form):
    # 正则验证:不能为空,6-18
    username=fields.CharField(
        max_length=18,
        min_length=6,
        required=True,
        error_messages={
            'required':'用户名不能为空',
            'min_length':'用户名最少需要6个字符',
            'max_length':'用户名最多可用18个字符',
        })
    # 正则验证: 不能为空,16+
    password = fields.CharField(
        min_length=10,
        required=True,
        error_messages={
            'required': '密码不能为空',
            'min_length': '密码最少需要10个字符',
        }
    )

在views.py函数内部的处理:

from django.shortcuts import render,HttpResponse,redirect
from django.forms import Form
from django.forms import fields
class LoginForm(Form):
    # 正则验证:不能为空,6-18
    username=fields.CharField(
        max_length=18,
        min_length=6,
        required=True,
        error_messages={
            'required':'用户名不能为空',
            'min_length':'用户名最少需要6个字符',
            'max_length':'用户名最多可用18个字符',
        })
    # 正则验证: 不能为空,16+
    password = fields.CharField(
        min_length=10,
        required=True,
        error_messages={
            'required': '密码不能为空',
            'min_length': '密码最少需要10个字符',
        }
    )

def login(request):
    if request.method == "GET":
        return render(request,'login.html')
    else:
       obj = LoginForm(request.POST)
       if obj.is_valid():
           # 用户输入格式正确
           print(obj.cleaned_data) # 字典类型
           return redirect('http://www.cnblogs.com/xuyuanyuan123/')
       else:
           # 用户输入格式错误
           return render(request,'login.html',{'obj':obj})

url.py

from app01 import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^login.html$', views.login),

]

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <link rel="stylesheet" href="/static/plugins/bootstrap-3.3.7-dist/css/bootstrap.css" />
    <link rel="stylesheet" href="/static/plugins/font-awesome-4.7.0/css/font-awesome.css" />
    <style>
        body {
            background: url("http://p1.so.qhimgs1.com/bdr/_240_/t01496c13d1b5e3b8e1.gif");
            background-size: 100%;
        }
        .login{
            width: 550px;
            height: 360px;
            background-color: papayawhip;
            text-align: center;
            margin-top: 20px;
            margin-left: 510px;
            position: fixed;

        }
        .user{
            margin-top: 100px;
            font-size: 20px;
        }
        .pwd{
            margin-top: 30px;
            font-size: 20px;
        }
        .choise{
            margin-top: 20px;

        }

    </style>
</head>
<h1 style="text-align: center;font-size: 50px;font-style:normal;color:#b2dba1;margin-top: 170px">博客园</h1>
<body>

<form id="f1" method="post" action="/login.html" class="form-horizontal">
        <div class="login">
            {% csrf_token %}

            <div class="user">
              用户名:<input type="text" name="username">{{ obj.errors.username.0 }}
            </div>

            <div class="pwd">
              密 码:<input type="password" name="password">{{ obj.errors.password.0 }}
            </div>
            <div>
              <button type="submit" class="btn btn-primary">登录</button>
              <a class="btn btn-primary" onclick="Ajaxlogin()">Ajax登录</a>
              <a class="btn btn-primary" href="/register.html">注册</a>
            </div>
            {{ msg }}
        </div>

</form>
<script src="/static/jquery-1.12.4.js"></script>

</body>
</html>
View Code

执行的效果图是:

2、form类

创建Form类时,主要涉及到 【字段】 和 【插件】

字段:用于对用户请求数据的验证

插件:用于自动生成HTML;

(1)、Django内置字段如下

Field
    required=True,               是否允许为空
    widget=None,                 HTML插件
    label=None,                  用于生成Label标签或显示内容
    initial=None,                初始值
    help_text='',                帮助信息(在标签旁边显示)
    error_messages=None,         错误信息 {'required': '不能为空', 'invalid': '格式错误'}
    show_hidden_initial=False,   是否在当前插件后面再加一个隐藏的且具有默认值的插件(可用于检验两次输入是否一直)
    validators=[],               自定义验证规则
    localize=False,              是否支持本地化
    disabled=False,              是否可以编辑
    label_suffix=None            Label内容后缀

示例:

class TestForm(forms.Form):
    user = fields.CharField(
        required=True,
        max_length=12,
        min_length=3,
        error_messages={},
        widget = widgets.TextInput(attrs={"class":123}),  # 定制html插件,属性:用attrs参数
        # widget= widgets.Textarea()
        label="姓名",
        initial='laiying',
        show_hidden_initial=False,
        # validators=[]  #自定制验证规则
        # disabled=True
        label_suffix=":"
 
    )

Django内置字段如下:

CharField(Field)
    max_length=None,             最大长度
    min_length=None,             最小长度
    strip=True                   是否移除用户输入空白
  
IntegerField(Field)
    max_value=None,              最大值
    min_value=None,              最小值
  
FloatField(IntegerField)
    ...
  
DecimalField(IntegerField)
    max_value=None,              最大值
    min_value=None,              最小值
    max_digits=None,             总长度
    decimal_places=None,         小数位长度
  
BaseTemporalField(Field)
    input_formats=None          时间格式化  
  
DateField(BaseTemporalField)    格式:2015-09-01
TimeField(BaseTemporalField)    格式:11:12
DateTimeField(BaseTemporalField)格式:2015-09-01 11:12
  
DurationField(Field)            时间间隔:%d %H:%M:%S.%f
    ...
  
RegexField(CharField)
    regex,                      自定制正则表达式
    max_length=None,            最大长度
    min_length=None,            最小长度
    error_message=None,         忽略,错误信息使用 error_messages={'invalid': '...'}
  
EmailField(CharField)     
    ...
  
FileField(Field)
    allow_empty_file=False     是否允许空文件
  
ImageField(FileField)     
    ...
    注:需要PIL模块,pip3 install Pillow
    以上两个字典使用时,需要注意两点:
        - form表单中 enctype="multipart/form-data"
        - view函数中 obj = MyForm(request.POST, request.FILES)
  
URLField(Field)
    ...
  
  
BooleanField(Field) 
    ...
  
NullBooleanField(BooleanField)
    ...
  
ChoiceField(Field)
    ...
    choices=(),                选项,如:choices = ((0,'上海'),(1,'北京'),)
    required=True,             是否必填
    widget=None,               插件,默认select插件
    label=None,                Label内容
    initial=None,              初始值
    help_text='',              帮助提示
  
  
ModelChoiceField(ChoiceField)
    ...                        django.forms.models.ModelChoiceField
    queryset,                  # 查询数据库中的数据
    empty_label="---------",   # 默认空显示内容
    to_field_name=None,        # HTML中value的值对应的字段
    limit_choices_to=None      # ModelForm中对queryset二次筛选
      
ModelMultipleChoiceField(ModelChoiceField)
    ...                        django.forms.models.ModelMultipleChoiceField
  
  
      
TypedChoiceField(ChoiceField)
    coerce = lambda val: val   对选中的值进行一次转换
    empty_value= ''            空值的默认值
  
MultipleChoiceField(ChoiceField)
    ...
  
TypedMultipleChoiceField(MultipleChoiceField)
    coerce = lambda val: val   对选中的每一个值进行一次转换
    empty_value= ''            空值的默认值
  
ComboField(Field)
    fields=()                  使用多个验证,如下:即验证最大长度20,又验证邮箱格式
                               fields.ComboField(fields=[fields.CharField(max_length=20), fields.EmailField(),])
  
MultiValueField(Field)
    PS: 抽象类,子类中可以实现聚合多个字典去匹配一个值,要配合MultiWidget使用
  
SplitDateTimeField(MultiValueField)
    input_date_formats=None,   格式列表:['%Y--%m--%d', '%m%d/%Y', '%m/%d/%y']
    input_time_formats=None    格式列表:['%H:%M:%S', '%H:%M:%S.%f', '%H:%M']
  
FilePathField(ChoiceField)     文件选项,目录下文件显示在页面中
    path,                      文件夹路径
    match=None,                正则匹配
    recursive=False,           递归下面的文件夹
    allow_files=True,          允许文件
    allow_folders=False,       允许文件夹
    required=True,
    widget=None,
    label=None,
    initial=None,
    help_text=''
  
GenericIPAddressField
    protocol='both',           both,ipv4,ipv6支持的IP格式
    unpack_ipv4=False          解析ipv4地址,如果是::ffff:192.0.2.1时候,可解析为192.0.2.1, PS:protocol必须为both才能启用
  
SlugField(CharField)           数字,字母,下划线,减号(连字符)
    ...
  
UUIDField(CharField)           uuid类型

需求: 在页面上不用加self直接显示input框

 

代码如下:

text.html

<body>
  {{txt}}
</body>

views.py

def test(request):
    if request.methon == 'GET':
    txt = "<input type='text' />"
    from django.utils.safestring import mark_safe
    txt = mark_safe(txt)
    return render(request,'text.html',{'txt':txt})

注:UUID是根据MAC以及当前时间等创建的不重复的随机字符串

>>> import uuid
 
    # make a UUID based on the host ID and current time
    >>> uuid.uuid1()    # doctest: +SKIP
    UUID('a8098c1a-f86e-11da-bd1a-00112444be1e')
 
    # make a UUID using an MD5 hash of a namespace UUID and a name
    >>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')
    UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')
 
    # make a random UUID
    >>> uuid.uuid4()    # doctest: +SKIP
    UUID('16fd2706-8baf-433b-82eb-8c7fada847da')
 
    # make a UUID using a SHA-1 hash of a namespace UUID and a name
    >>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
    UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d')
 
    # make a UUID from a string of hex digits (braces and hyphens ignored)
    >>> x = uuid.UUID('{00010203-0405-0607-0809-0a0b0c0d0e0f}')
 
    # convert a UUID to a string of hex digits in standard form
    >>> str(x)
    '00010203-0405-0607-0809-0a0b0c0d0e0f'
 
    # get the raw 16 bytes of the UUID
    >>> x.bytes
    b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'
 
    # make a UUID from a 16-byte string
    >>> uuid.UUID(bytes=x.bytes)
    UUID('00010203-0405-0607-0809-0a0b0c0d0e0f')
View Code

(2)、Django内置插件:

TextInput(Input)
NumberInput(TextInput)
EmailInput(TextInput)
URLInput(TextInput)
PasswordInput(TextInput)
HiddenInput(TextInput)
Textarea(Widget)
DateInput(DateTimeBaseInput)
DateTimeInput(DateTimeBaseInput)
TimeInput(DateTimeBaseInput)
CheckboxInput
Select
NullBooleanSelect
SelectMultiple
RadioSelect
CheckboxSelectMultiple
FileInput
ClearableFileInput
MultipleHiddenInput
SplitDateTimeWidget
SplitHiddenDateTimeWidget
SelectDateWidget
View Code

常用选择插件

<strong># 单radio,值为字符串</strong>
# user = fields.CharField(
#     initial=2,
#     widget=widgets.RadioSelect(choices=((1,'上海'),(2,'北京'),))
# )
  
<strong># 单radio,值为字符串</strong>
# user = fields.ChoiceField(
#     choices=((1, '上海'), (2, '北京'),),
#     initial=2,
#     widget=widgets.RadioSelect
# )
  
<strong># 单select,值为字符串</strong>
# user = fields.CharField(
#     initial=2,
#     widget=widgets.Select(choices=((1,'上海'),(2,'北京'),))
# )
  
<strong># 单select,值为字符串</strong>
# user = fields.ChoiceField(
#     choices=((1, '上海'), (2, '北京'),),
#     initial=2,
#     widget=widgets.Select
# )
  
<strong># 多选select,值为列表</strong>
# user = fields.MultipleChoiceField(
#     choices=((1,'上海'),(2,'北京'),),
#     initial=[1,],
#     widget=widgets.SelectMultiple
# )
  
<strong># 单checkbox</strong>
# user = fields.CharField(
#     widget=widgets.CheckboxInput()
# )
  
<strong># 多选checkbox,值为列表</strong>
# user = fields.MultipleChoiceField(
#     initial=[2, ],
#     choices=((1, '上海'), (2, '北京'),),
#     widget=widgets.CheckboxSelectMultiple
# )

示例:

select的多种写法:

a、单选

     # 下拉框的方法1:
    # cls_id = fields.IntegerField(
    #     widget=widgets.Select(choices=[(1,'上海'),(2,'北京')]))
    # 下拉框的方法2:
    # cls_id = fields.CharField(
    #     widget=widgets.Select(choices=[(1,'昌平区'),(2,'海淀区'),(3,'朝阳区')]))
    # 下拉框的方法3:
    # cls_id = fields.ChoiceField(
    #     choices=[(1,'10号线'),(2,'8号线'),(3,'5号线')]
    # )

b、多选

 #多选下拉框(有自定义属性)
 # xdb = fields.MultipleChoiceField(
 #     choices=[(1, '朝阳区'), (2, '海淀区'), (3, '昌平区')],
 #     widget=widgets.SelectMultiple(attrs={'class':'c1'}) #后面参数是定制属性
 # )
     #单选checkbox
 # xdb = fields.CharField(
 #     widget=widgets.CheckboxInput()
 # )
  #多选checkbox (多个checkbox,二选一)
 # xdb = fields.MultipleChoiceField(
 #     initial=[2, ],
 #     choices=((1, '上海'), (2, '北京'),),
 #     widget=widgets.CheckboxSelectMultiple
 # )
 
#多个选项Radio (互斥 三选一)
 # xdb =  fields.ChoiceField(
 #     choices=((1, '上海'), (2, '北京'),(3, '北京1'),),
 #     initial=2,
 #     widget=widgets.RadioSelect
 # )

 

用form实现验证的功能:(一对一、一对多、多对多)

1、单表的操作:(一对一)====>班级表

首先建立一个新的目录:(该结构如下)

首先先建立表格,在models.py内写入:

from django.db import models

class Classes(models.Model):
    cname=models.CharField(max_length=32)

class Student(models.Model):
    sname=models.CharField(max_length=32)
    email=models.CharField(max_length=32)
    age=models.IntegerField(max_length=16)
    cls=models.ForeignKey('Classes')

class Teacher(models.Model):
    tname=models.CharField(max_length=32)
    c2t=models.ManyToManyField('Classes')
    # c2t=models.ManyToManyField('Classes')相当于建立的第四张关系表

 urls.py

from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    # =======班级表:单表操作=====
    url(r'^classes.html$',views.classes),
    url(r'^add_class.html$',views.add_class),
    url(r'^edit_class/(\d+)',views.edit_class),
    url(r'^del_class/(\d+)',views.del_class),

    # ======班级表和学生表操作:一对多操作=====
    url(r'^student.html$',views.student),
    url(r'^add_student.html$',views.add_student),
    url(r'^edit_student/(\d+)',views.edit_student),
    url(r'^del_student/(\d+)',views.del_student),

    # ===========班级表和老师表操作:多对多操作=========
    url(r'^teacher.html$',views.teacher),
    url(r'^add_teacher.html$',views.add_teacher),
    url(r'^edit_teacher/(\d+)',views.edit_teacher),
    url(r'^del_teacher/(\d+)',views.del_teacher),
]

views.py

from django.shortcuts import render,redirect,HttpResponse
from django.forms import Form
from app01 import models
from django.forms import fields
from django.forms import widgets
# =========================班级表操作=========================
class ClassForm(Form):
    cname=fields.RegexField('老男孩\d+')

def classes(request):
    cls_list=models.Classes.objects.all()
    return render(request,"classes.html",{"cls_list":cls_list})

def add_class(request):
    if request.method=="GET":
        obj=ClassForm()
        return render(request,"add_class.html",{"obj":obj})
    else:
        obj=ClassForm(request.POST)
        print(obj)
        if obj.is_valid():
            # obj.cleaned_data是字典格式
            # print(obj.cleaned_data)
            #如果用户输入的信息无误的话,则需要在数据库中插入用户输入的数据
            models.Classes.objects.create(**obj.cleaned_data)
            return redirect("/classes.html")
        return render(request,'add_class.html',{'obj':obj})

def edit_class(request,nid):
    if request.method=="GET":
        res=models.Classes.objects.filter(id=nid).first()
        # 让页面显示初始值
        # obj = ClassForm(data={'cname': '老男孩3期'})#这里面含有验证规则,有错误信息显示
        obj=ClassForm(initial={'cname':res.cname})
        return render(request,"edit_class.html",{'nid':nid,'obj':obj})
    else:
        obj=ClassForm(request.POST)
        if obj.is_valid():
            models.Classes.objects.filter(id=nid).update(**obj.cleaned_data)
            return redirect("/classes.html")
        return render(request,"edit_class.html",{'nid':nid,'obj':obj})

def del_class(request,nid):
    models.Classes.objects.filter(id=nid).delete()
    return redirect("/classes.html")

classes.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>班级列表</h1>
<div>
    <a href="/add_class.html">添加班级</a>
</div>
<ul>
    {% for i in cls_list %}
        <li>
        {{ i.cname }}|<a href="/edit_class/{{ i.id }}">编辑</a>|<a href="/del_class/{{ i.id }}">删除</a>
        </li>
    {% endfor %}
</ul>
</body>
</html>

add_class.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>添加班级</h1>
<form method="POST" action="/add_class.html">
    {% csrf_token %}
    <p>
        {{ obj.cname }}{{ obj.errors.cname.0 }}
    </p>
    <p>
        <input type="submit" value="提交">
    </p>
</form>
</body>
</html>

edit_class.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>编辑班级</h1>
<form action="/edit_class/{{ nid }}" method="POST">
    {% csrf_token %}
    <p>
        {{ obj.cname }}{{ obj.errors.cname.0 }}
    </p>
    <input type="submit" value="提交">

</form>
</body>
</html>

页面展示效果图:

 

2、form验证操作:(一对多)====>班级表和学生表操作:

views.py

from django.shortcuts import render,redirect,HttpResponse
from django.forms import Form
from app01 import models
from django.forms import fields
from django.forms import widgets
# ================一对多:学生表操作======
class StudentForm(Form):
    sname=fields.CharField(
        min_length=2,
        max_length=6,
        widget=widgets.TextInput(attrs={'class':'form-control'})#给标签的input框加一个样式
    )
    email=fields.EmailField(
        widget=widgets.TextInput(attrs={'class': 'form-control'})
    )
    age=fields.IntegerField(
        min_value=18,
        max_value=30,
        widget=widgets.TextInput(attrs={'class': 'form-control'})
    )
    # 下拉框的方法1:
    # cls_id = fields.IntegerField(
    #     widget=widgets.Select(choices=[(1,'上海'),(2,'北京')]))
    # 下拉框的方法2:
    # cls_id = fields.CharField(
    #     widget=widgets.Select(choices=[(1,'昌平区'),(2,'海淀区'),(3,'朝阳区')]))
    # 下拉框的方法3:
    # cls_id = fields.ChoiceField(
    #     choices=[(1,'10号线'),(2,'8号线'),(3,'5号线')]
    # )
    cls_id=fields.IntegerField(
        # widget=widgets.Select(choices=[(1,'上海'),(2,'北京')])
        #在这里需要用列表套元祖的方式,所以用values_list
        widget=widgets.Select(choices=models.Classes.objects.values_list('id', 'cname'),attrs={'class': 'form-control'})
    )

def student(request):
    s_list=models.Student.objects.all()
    return render(request,"student.html",{"s_list":s_list})

def add_student(request):
    if request.method=="GET":
        obj=StudentForm()
        return render(request,"add_student.html",{'obj':obj})
    else:
        obj=StudentForm(request.POST)
        if obj.is_valid():
            models.Student.objects.create(**obj.cleaned_data)
            return redirect("/student.html")
        else:
            return render(request, "add_student.html", {'obj': obj})

def edit_student(request,nid):
    if request.method=="GET":
        ret=models.Student.objects.filter(id=nid).values("sname","email","age","cls_id").first()
        obj=StudentForm(initial=ret)
        return render(request,"edit_student.html",{'nid':nid,'obj':obj})
    else:
        obj=StudentForm(request.POST)
        if obj.is_valid():
            models.Student.objects.filter(id=nid).update(**obj.cleaned_data)
            return redirect("/student.html")
        else:
            return render(request, "edit_student.html", {'nid': nid,'obj':obj})

def del_student(request,nid):
    models.Student.objects.filter(id=nid).delete()
    return redirect("/student.html")

student.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>学生列表</h1>
<a href="/add_student.html">添加学生</a>
<ul>
    {% for i in s_list %}
        <li>
            {{ i.sname }}/{{ i.email }}/{{ i.age }}/{{ i.cls_id }}/{{ i.cls.title }}|<a href="/edit_student/{{ i.id }}">编辑</a>|<a href="/del_student/{{ i.id }}">删除</a>
        </li>
    {% endfor %}
</ul>

</body>
</html>

add_student.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>添加学生</h1>
<form action="/add_student.html" method="POST">
    {% csrf_token %}
    <p>
        {{ obj.sname }}{{ obj.errors.sname.0 }}
    </p>
    <p>
        {{ obj.email }}{{ obj.errors.email.0 }}
    </p>
    <p>
        {{ obj.age }}{{ obj.errors.age.0 }}
    </p>
    <p>
        {{ obj.cls_id }}{{ obj.errors.cls_id.0 }}
    </p>
    <input type="submit" value="提交" />
</form>

</body>
</html>

edit_student.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div style="width: 500px;margin: 0 auto;">
    <form class="form-horizontal" method="POST" action="/edit_student/{{ nid }}/">
        {% csrf_token %}
        <div class="form-group">
            <label class="col-sm-2 control-label">姓名:</label>

            <div class="col-sm-10">
                {{ obj.sname }}{{ obj.errors.sname.0 }}
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label">邮箱:</label>

            <div class="col-sm-10">
                {{ obj.email }}{{ obj.errors.email.0 }}
            </div>
        </div>
         <div class="form-group">
            <label class="col-sm-2 control-label">年龄:</label>

            <div class="col-sm-10">
                {{ obj.age }}{{ obj.errors.age.0 }}
            </div>
        </div>
         <div class="form-group">
            <label class="col-sm-2 control-label">班级:</label>

            <div class="col-sm-10">
                {{ obj.cls_id }}{{ obj.errors.cls_id.0 }}
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
                <input type="submit" class="btn btn-default" value="提交" />
            </div>
        </div>
    </form>
</div>
</body>
</html>

页面效果图展现:

 

3、form表单验证:班级表和老师表(多对多的关系)

views.py

from django.shortcuts import render,redirect,HttpResponse
from django.forms import Form
from app01 import models
from django.forms import fields
from django.forms import widgets
# ============多对多:老师表操作===============
class TeacherForm(Form):
    tname=fields.CharField(min_length=2)
    cls_name=fields.MultipleChoiceField(
        choices=models.Classes.objects.values_list("id","cname"),
        widget=widgets.SelectMultiple
    )

def teacher(request):
    t_list=models.Teacher.objects.all()
    return render(request,"teacher.html",{'t_list':t_list})

def add_teacher(request):
    if request.method=="GET":
        obj=TeacherForm()
        return render(request,"add_teacher.html",{'obj':obj})
    else:
        obj=TeacherForm(request.POST)
        if obj.is_valid():
            print(obj.cleaned_data)
            cls_name=obj.cleaned_data.pop("cls_name")
            row=models.Teacher.objects.create(**obj.cleaned_data)
            # print(cls_name)
            print(row)
            row.c2t.add(*cls_name)
            return redirect('/teacher.html')
        return render(request, "add_teacher.html", {'obj': obj})

def edit_teacher(request,nid):
    if request.method=="GET":
        res=models.Teacher.objects.filter(id=nid).first()#取到老师的id和老师的姓名
        #需要取到班级的id
        class_id=res.c2t.values_list("id")
        # print(class_id)#是一个字符串
        # cid_list=[]
        cid_list=list(zip(*class_id))[0] if list(zip(*class_id)) else []
        # 使用三元表达式cid_list=list(zip(*class_id))[0] if list(zip(*class_id)) else []
        obj=TeacherForm(initial={'tname':res.tname,'cid_list':cid_list})
        return render(request,"edit_teacher.html",{'nid':nid,'obj':obj})
    else:
        obj=TeacherForm(request.POST)
        if obj.is_valid():
            # print(obj.cleaned_data)#{'tname': 'alex', 'cls_name': ['1', '2']}
            cls_name=obj.cleaned_data.pop("cls_name")
            print(cls_name)
            ret=models.Teacher.objects.filter(id=nid).update(**obj.cleaned_data)
            res=models.Teacher.objects.filter(id=nid).first()
            # print(ret)
            print(res)
            # res.c2t.remove()
            res.c2t.set(cls_name)
            return redirect("/teacher.html")
        else:
            print("ok")
            return render(request, "edit_teacher.html", {'nid': nid, 'obj': obj})

def del_teacher(request,nid):
    models.Teacher.objects.filter(id=nid).delete()
    return redirect("/teacher.html")

teacher.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>老师列表</h1>
<a href="/add_teacher.html">添加老师</a>
<table border="1px">
    <thead>
        <tr>
            <th>老师ID</th>
            <th>老师姓名</th>
            <th>任教班级</th>
            <th>操作</th>
        </tr>
    </thead>
    <tbody>
        {% for i in t_list %}
            <tr>
                <th>{{ i.id }}</th>
                <th>{{ i.tname }}</th>
                <th>
                    {% for j in i.c2t.all %}
                        {{ j.cname }}
                    {% endfor %}
                </th>
                <th>
                    <a href="/edit_teacher/{{ i.id }}">编辑</a>
                    |
                    <a href="/del_teacher/{{ i.id }}">删除</a>
                </th>
            </tr>
        {% endfor %}
    </tbody>

</table>

</body>
</html>

add_teacher.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>添加老师</h1>
<form action="/add_teacher.html" method="POST">
    {% csrf_token %}
    <p>
        老师姓名:{{ obj.tname }}{{ obj.errors.tname.0 }}
    </p>
    <p>
        老师班级:{{ obj.cls_name }}{{ obj.errors.cls_name.0 }}
    </p>
    <input type="submit" value="提交">

</form>
</body>
</html>

edit_teacher.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>编辑老师</h1>
<form method="POST" action="/edit_teacher/{{ nid }}">
    {% csrf_token %}
    <p>
        {{ obj.tname }}{{ obj.errors.tname.0 }}
    </p>
    <p>
        {{ obj.cls_name }}{{ obj.errors.cls_name.0 }}
    </p>
    <input type="submit" value="提交">
</form>
</body>
</html>

页面展现效果图:

 

 

posted @ 2017-07-07 16:09  白木潇潇夕  阅读(452)  评论(0编辑  收藏  举报