1.modelform
class StudentStudyRecordModelForm(forms.ModelForm): class Meta: model = StudentStudyRecord fields = ["score","homework_note"] def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) for field in self.fields.values(): field.widget.attrs.update({"class":"form-control"})
2.view
from django.forms.models import modelformset_factory class EditStudentStudyRecordView(View): def get(self,request,edit_id): model_formset_cls = modelformset_factory(model=StudentStudyRecord,form=StudentStudyRecordModelForm,extra=0) queryset = StudentStudyRecord.objects.filter(classstudyrecord_id=edit_id) formset = model_formset_cls(queryset=queryset) class_study_record = ClassStudyRecord.objects.filter(pk=edit_id).first() title = class_study_record return render(request,"edit_studentstudyrecord.html",{"formset":formset,"title":title}) def post(self,request,edit_id): model_formset_cls = modelformset_factory(model=StudentStudyRecord, form=StudentStudyRecordModelForm, extra=0) formset = model_formset_cls(request.POST) if formset.is_valid(): formset.save() return redirect(request.path)
3.html
1 <form method="post" action=""> 2 {% csrf_token %} 3 {{ formset.management_form }}#必须有,否则发送post请求时会报错 4 5 <table class="table table-bordered"> 6 <thead> 7 <tr> 8 <th>姓名</th> 9 <th>考勤</th> 10 <th>作业成绩</th> 11 <th>作业评语</th> 12 </tr> 13 </thead> 14 <tbody> 15 {% for form in formset %} 16 <tr> 17 {{ form.id }} 18 <td>{{ form.instance.student }}</td> 19 <td>{{ form.instance.get_record_display }} </td> 20 <td>{{ form.score }} </td> 21 <td>{{ form.homework_note }}</td> 22 </tr> 23 {% endfor %} 24 </tbody> 25 </table> 26 <input type="submit" value="保存"> 27 </form>