ModelFormSet 基于modelform 实现的批量处理
前端:
<form method="post" action=""> {% csrf_token %} {{ formset.management_form }} <table class="table table-bordered"> <thead> <tr> <th>姓名</th> <th>考勤</th> <th>作业成绩</th> <th>作业评语</th> </tr> </thead> <tbody> {% for form in formset %} <tr> {{ form.id }} <td>{{ form.instance.student }}</td> <td>{{ form.instance.get_record_display }} </td> <td>{{ form.score }} </td> <td>{{ form.homework_note }}</td> </tr> {% endfor %} </tbody> </table> <input type="submit" value="保存"> </form>
在前端中使用的时候需要注意: {{ formset.management_form }} 这行代码必须加入。
视图与form:
from django.forms.models import modelformset_factory class StudentStudyRecordModelForm(forms.ModelForm): class Meta: model=StudentStudyRecord fields=["score","homework_note"] class RecordScoreView(View): def get(self, request,class_study_record_id): model_formset_cls=modelformset_factory(model=StudentStudyRecord,form=StudentStudyRecordModelForm,extra=0) queryset = StudentStudyRecord.objects.filter(classstudyrecord=class_study_record_id) formset = model_formset_cls(queryset=queryset) return render(request,"student/record_score.html",locals()) def post(self, request,class_study_record_id): model_formset_cls = modelformset_factory(model=StudentStudyRecord, form=StudentStudyRecordModelForm, extra=0) queryset = StudentStudyRecord.objects.filter(classstudyrecord=class_study_record_id) print("request.POST",request.POST) formset=model_formset_cls(request.POST) # 实例化对象 if formset.is_valid(): formset.save() print(formset.errors) return redirect(request.path)
也就是说使用时需注意 modelformset_factory()中有两个参数必须给值,model绑定的是模型表,form绑定的是与之相关的modelform,