s4 学员管理Form

学员管理示例(Form组件实现)

- 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'^class_list/', views.class_list),
        url(r'^add_class/', views.add_class),
        url(r'^edit_class/(\d+)/', views.edit_class),

        url(r'^student_list/', views.student_list),
        url(r'^add_student/', views.add_student),
        url(r'^edit_student/(\d+)/', views.edit_student),

        url(r'^teacher_list/', views.teacher_list),
        url(r'^add_teacher/', views.add_teacher),
        url(r'^edit_teacher/(\d+)/', views.edit_teacher),

    ]

- models.py

    from django.db import models

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

        # def __str__(self):
        #     return self.title

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

    class Teacher(models.Model):
        tname = models.CharField(max_length=32)
        c2t =models.ManyToManyField('Classes')
        
        

- views.py

    from django.shortcuts import render,redirect
    from app01 import models
    from django.forms import Form
    from django.forms import fields
    from django.forms import widgets

    class ClassForm(Form):
        title = fields.RegexField('全栈\d+')

    def class_list(request):
        cls_list = models.Classes.objects.all()
        return render(request,'class_list.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)
            if obj.is_valid():
                models.Classes.objects.create(**obj.cleaned_data)
                return redirect('/class_list/')
            return render(request,'add_class.html',{'obj':obj})

    def edit_class(request,nid):
        if request.method=='GET':
            row = models.Classes.objects.filter(id=nid).first()
            # 页面显示初始值

            # obj = ClassForm(data={'title':row.title})
            # obj = ClassForm(data={'title':'xxxxxxxxxx'})
            # data=默认进行校验
            obj = ClassForm(initial={'title':row.title})
            # initial= 默认不进行校验
            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('/class_list/')
            return render(request,'edit_class.html',{'nid':nid,'obj':obj})




    class StudentForm(Form):
        name = fields.CharField(
            min_length=2,
            max_length=6,
            widget=widgets.TextInput(attrs={'class':'form-control'})
        )
        email=fields.EmailField(widget=widgets.TextInput(attrs={'class':'form-control'}))
        age = fields.IntegerField(min_value=18,max_value=25,widget=widgets.TextInput(attrs={'class':'form-control'}))

        # 单选实现:ChoiceField Select
        cls_id=fields.ChoiceField(
            # widget=widgets.Select(choices=[(1,'上海'),(2,'北京')])
            # widget=widgets.Select(choices=models.Classes.objects.values_list('id','title'),attrs={'class':'form-control'})
            widget=widgets.Select(attrs={'class':'form-control'})
        )
        def __init__(self,*args,**kwargs):
            super(StudentForm,self).__init__(*args,**kwargs)
            self.fields['cls_id'].choices=models.Classes.objects.values_list('id','title')

    def student_list(request):
        stu_list= models.Student.objects.all()
        return render(request,'student_list.html',{'stu_list':stu_list})

    def add_student(request):
        if request.method=='GET':
            obj = StudentForm(initial={'cls_id':[5,]})
            return render(request,'add_student.html',{'obj':obj})
        else:
            obj=StudentForm(request.POST)
            if obj.is_valid():
                # print(obj.cleaned_data)
                models.Student.objects.create(**obj.cleaned_data)
                return redirect('/student_list/')
            return render(request,'add_student.html',{'obj':obj})

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




    def teacher_list(request):
        tea_list=models.Teacher.objects.all()
        return render(request,'teacher_list.html',{'tea_list':tea_list})

    # from django.forms import models as form_model
    class TeacherForm(Form):
        tname =fields.CharField(min_length=3)

        # 自带多选实现,依赖model的 __str__
        # xx = form_model.ModelMultipleChoiceField(queryset=models.Classes.objects.all())
        # xx = form_model.ModelChoiceField(queryset=models.Classes.objects.all())

        # xx =fields.CharField(
        #     # request.POST.get('xx')
        #     # widget=widgets.Select(choices=models.Classes.objects.values_list('id','title'))
        #     widget=widgets.SelectMultiple(choices=models.Classes.objects.values_list('id','title'))
        #     # 'xx':"['1','2']" 字符串 不能满足
        # )

        # 多选实现:fields.MultipleChoiceField choices
        c2t =fields.MultipleChoiceField(
            # choices=models.Classes.objects.values_list('id','title'),
            widget=widgets.SelectMultiple()
        )
        def __init__(self,*args,**kwargs):
            super(TeacherForm,self).__init__(*args,**kwargs)
            self.fields['c2t'].choices=models.Classes.objects.values_list('id','title')

    def add_teacher(request):
        if request.method=="GET":
            obj = TeacherForm()
            return render(request,'add_teacher.html',{'obj':obj})
        else:
            obj = TeacherForm(request.POST)
            print(request.POST)
            print(obj.is_valid())
            if obj.is_valid():
                # 多对多数据添加
                print(obj.cleaned_data)
                xx = obj.cleaned_data.pop('c2t') # [1,2]
                # models.Teacher.objects.create(tname=obj.cleaned_data['tname'])
                row = models.Teacher.objects.create(**obj.cleaned_data)
                print(row)
                row.c2t.add(*xx)
                return redirect('/teacher_list/')
            return render(request,'add_teacher.html',{'obj':obj})

    def edit_teacher(request,nid):
        if request.method=="GET":
            row = models.Teacher.objects.filter(id=nid).first()
            class_ids=row.c2t.values_list('id')
            # id_list=[]
            id_list = list(zip(*class_ids))[0] if list(zip(*class_ids)) else []
            obj=TeacherForm(initial={'tname':row.tname,'c2t':id_list})
            return render(request,'edit_teacher.html',{'obj':obj,'nid':nid})  #[1,2]
        else:
            obj = TeacherForm(request.POST)
            print(request.POST)
            print(obj.is_valid())
            if obj.is_valid():
                # 多对多数据添加
                print(obj.cleaned_data)
                xx = obj.cleaned_data.pop('c2t') # [1,2]
                # models.Teacher.objects.create(tname=obj.cleaned_data['tname'])
                models.Teacher.objects.filter(id=nid).update(**obj.cleaned_data)
                obj = models.Teacher.objects.filter(id = nid).first()
                obj.c2t.set(xx)
                return redirect('/teacher_list/')
            return render(request,'add_teacher.html',{'obj':obj,'nid':nid})
            
            

- class_list.html

    <h1>班级列表</h1>
    <div><a href="/add_class/">添加</a></div>
    <ul>
        {% for row in cls_list %}
            <li>{{ row.title }}<a href="/edit_class/{{ row.id }}/">编辑</a></li>
        {% endfor %}
    </ul>

- add_class.html

    <h1>添加班级</h1>
    <form action="/add_class/" method="POST" novalidate>
        {% csrf_token %}
        {{ obj.title }}{{ obj.errors.title.0 }}
        <p><input type="submit"value="提交"></p>
    </form>

- edit_class.html

    <h1>编辑班级</h1>
    <form action="/edit_class/{{ nid }}/"method="POST">
        {% csrf_token%}
        <p>{{ obj.title }}{{ obj.errors.title.0 }}</p>
        <input type="submit"value="提交">
    </form>


    
    
- student_list.html

    <h1>学生列表</h1>
    <a href="/add_student/">添加</a>
    <ul>
        {% for row in stu_list %}
            <li>{{ row.name }}-{{ row.email }}-{{ row.age }}-{{ row.cls_id }}-{{ row.cls.title }}<a href="/edit_student/{{ row.id }}/">编辑</a></li>
        {% endfor %}
    </ul>

- add_student.html

    <h1>添加学生</h1>
    <form action="/add_student/" method="POST"novalidate>
        {% csrf_token %}
        <p>{{ obj.name }}{{ obj.errors.name.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>

- edit_student.html
    # bootstrap-3.3.7-dist

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title></title>
        <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css">
    </head>
    <body>
    <h1>编辑学生</h1>
    <form action="/edit_student/{{ nid }}" method="POST" novalidate>
        {% csrf_token %}
        <p>{{ obj.name }}{{ obj.errors.name.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>

    <div style="width: 500px;margin: 0 auto">
        <h1>编辑学生</h1>
        <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.name }}
                </div>
            </div>
            <div class="form-group">
                <label  class="col-sm-2 control-label">年龄</label>
                <div class="col-sm-10">
                    {{ obj.age }}
                </div>
            </div>
            <div class="form-group">
                <label  class="col-sm-2 control-label">邮箱</label>
                <div class="col-sm-10">
                    {{ obj.email }}
                </div>
            </div>
            <div class="form-group">
                <label  class="col-sm-2 control-label">班级</label>
                <div class="col-sm-10">
                    {{ obj.cls_id }}
                </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>


- teacher_list.html

    <h1>老师列表</h1>
    <div><a href="/add_teacher/">添加</a></div>
    <table border="1">
        <thead>
            <tr>
                <th>ID</th>
                <th>老师姓名</th>
                <th>任教班级</th>
                <th>编辑</th>
            </tr>
        </thead>
        <tbody>
            {% for row in tea_list %}
                <tr>
                    <td>{{ row.id }}</td>
                    <td>{{ row.tname }}</td>
                    <td>
                        {% for item in row.c2t.all %}
                            <span>{{ item.title }}</span>
                        {% endfor %}
                    </td>
                    <td>
                        <a href="/edit_teacher/{{ row.id }}/">编辑</a>
                    </td>
                </tr>
            {% endfor %}
        </tbody>
    </table>

- add_teacher.html

    <h1>添加老师</h1>
    <form action="/add_teacher/"method="POST">
        {% csrf_token %}
        <p>姓名:{{ obj.tname }}{{ obj.errors.tname.0}}</p>
        <p>班级:{{ obj.c2t }}{{ obj.errors.c2t.0 }}</p></p>
        <input type="submit"value="提交">
    </form>

- edit_teacher.html

    <h1>编辑老师</h1>
    <form action="/edit_teacher/{{ nid }}/" method="POST">
        {% csrf_token %}
        {{ obj.tname }}
        {{ obj.c2t }}
        <input type="submit"value="提交">
    </form>

posted @ 2020-01-18 21:11  badweather  阅读(88)  评论(0编辑  收藏  举报