Loading

formset批量处理form表单数据

 

Formset(表单集)是多个表单的集合。Formset在Web开发中应用很普遍,它可以让用户在同一个页面上提交多张表单,一键添加多个数据

class StudentStudyRecordModel(forms.ModelForm):
    class Meta:
        model=StudentStudyRecord
        fields=['score','homework_note']
view视图
复制代码
from django.forms.models import modelformset_factory

class Student_study_record(View):
def get(self,request):
        model_formset_cls=modelformset_factory(model=StudentStudyRecord,form=StudentStudyRecordModel,extra=0)
        queryset=StudentStudyRecord.objects.filter(classstudyrecord__id=request.GET.get('pk')) #批量操作的queryset
        formset=model_formset_cls(queryset=queryset)
        return render(request, 'students/Student_study_record.html', locals())

    def post(self,request):
        model_formset_cls = modelformset_factory(model=StudentStudyRecord, form=StudentStudyRecordModel, extra=0)
        formset=model_formset_cls(request.POST)  #与modelform校验基本一致,就是不用穿instance了
        if formset.is_valid():
            formset.save()
            return redirect('/class_study_record/')
        else:
            print('formset.errors##################',formset.errors)
            return self.get(request)
复制代码

templates模版

复制代码
            <form action="" method="post" novalidate>

                <table class="table table-hover table-striped" style="margin-top: 20px">
                    <thead>
                        <tr>
                            <td>编号</td>
                            <td>姓名</td>
                            <td>考勤</td>
                            <td>成绩</td>
                            <td>批语</td>
                        </tr>
                    </thead>
                    <tbody>
{#                     必须有,不然会报错#}
                    {{ formset.management_form }}
                    {% for form in formset %}
                        <tr>
                            <td>{{ form.id }}</td>           # 必须有form.id
                            <td>{{ form.instance.student }}</td>    #instance是显示具体的某个对象的值,而不是多选框(不能修改)
                            <td>{{ form.instance.get_record_display }}</td>  
                            <td>{{ form.score }}</td>
                            <td>{{ form.homework_note }}</td>
                            {% csrf_token %}
                        </tr>
                    {% endfor %}
                    </tbody>
                </table>
                <button class=" btn btn-success btn-sm pull-right" style="margin: 30px;">提交</button>
            </form>
复制代码
posted @ 2019-04-22 21:06  Ellisonzhang  阅读(190)  评论(1编辑  收藏  举报