https://www.cnblogs.com/apollo1616/articles/9990717.html

本文是基于上一篇文章的改进版,利用插件modelformset_factory完成上文中实现的手动添加

urls.py文件

from django.contrib import admin
from django.urls import path,re_path
from app01 import views


urlpatterns = [
    re_path('record_score/(\d+)/', views.RecordScoreView.as_view(), name="record_score"),
]

forms.py文件

from django.forms.models import modelformset_factory
class StudentStudyRecordModelForm(forms.ModelForm):
    class Meta:
        model=StudentStudyRecord
        fields=["score","homework_note"]

views.py文件

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)

html文件

<div class="panel-heading">学习记录</div>
    <div class="panel-body">
        <div style="width: 680px;margin: 0 auto;">
            <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 }}    # 这里只写了一层for循环,所以手动写字段,必须把id字段写上 <td>{{ form.student }}</td> <td>{{ form.record }} {{ form.record.errors.0 }}</td> <td>{{ form.score }} {{ form.score.errors.0 }}</td> <td>{{ form.homework_note }} {{ form.homework_note.errors.0 }}</td> </tr> {% endfor %} </tbody> </table> <input type="submit" value="保存"> </form> </div> </div> </div>