Django重新整理4---ModelForm-set(批量處理資料)
阿新 • • 發佈:2018-11-21
1.
#引用modelformset from django.forms.models import modelformset_factory #必須繼承forms.ModelForm! class StudentStudyRecordModelForm(forms.ModelForm): class Meta: #需要建立關聯的表StudentStudyRecord model = StudentStudyRecord #score", "homework_note 顯示的欄位 fields = ["score", "homework_note"]
2.
class RecordScoreView(View): def get(self, request, class_study_record_id): # modelformset_factory固定的寫法 ,model=StudentStudyRecord這是需要關聯的表名,form後邊是我們上邊的新建類名 , extra=0 不加它預設資料多一行 model_formset_cls = modelformset_factory(model=StudentStudyRecord, form=StudentStudyRecordModelForm, extra=0) queryset= StudentStudyRecord.objects.filter(classstudyrecord=class_study_record_id) print(class_study_record_id) #2 第2天的課程 print("queryset",queryset) #查詢第2天課程的學生記錄 formset = model_formset_cls(queryset=queryset) return render(request, "record_score.html", locals()) defpost(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) #??????????????????????????????// print("formset",formset) print(123456789) #判斷是否通過校驗 if formset.is_valid(): formset.save() # print(formset.errors) return redirect(request.path)
3.
#record_score.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css"> </head> <body> <h3>錄入{{ class_study_record_obj.class_obj }}day{{ class_study_record_obj.day_num }}成績</h3> <div class="panel panel-default"> <div class="panel-heading">學習記錄</div> <div class="panel-body"> <div style="width: 700px;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 }} <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> </div> </div> </div> </body> </html>