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>
当你的才华还撑不起你的野心的时候,你就应该静下心来学习;
当你的能力还驾驭不了你的目标时,就应该沉下心来历练。