Django中利用modelformset_factory实现批量添加操作
完整项目链接:https://www.cnblogs.com/WiseAdministrator/articles/11073919.html
urls.py文件:
from django.conf.urls import url
from django.contrib import admin
from web.views import control, customer, enrollment, my_customer, record, student
urlpatterns = [
# 学生学习记录信息
url(r'^study_record/(\d+)/', student.StudyRecordDeialView.as_view(), name='study_record'),
]
forms.py文件:
from django import forms from web import models # 学生学习记录ModeForm class StudyRecordDeialModelForm(forms.ModelForm): class Meta: model = models.StudentStudyRecord # fields = '__all__' fields = ['score', 'homework_note'] def __init__(self, *args, **kwargs): super(StudyRecordDeialModelForm, self).__init__(*args, **kwargs) for field in self.fields: self.fields[field].widget.attrs.update({ "class": "form-control", })
views.py文件:
from web import models
from django.views import View
from django.shortcuts import redirect, render, HttpResponse, reverse
from django.forms.models import modelformset_factory # queryset
from web.forms.studyrecord_form import StudyRecordDeialModelForm
# 学生学习记录信息
class StudyRecordDeialView(View):
def get(self, request, class_record_id):
# 通过当前学生记录id找到班级记录对象
class_record_obj = models.ClassStudyRecord.objects.get(pk=class_record_id)
# 找到班级记录找到对应的所有的学生记录
all_study_recored = models.StudentStudyRecord.objects.filter(
classstudyrecord=class_record_obj,
)
# 创建一个modelformset_factory对象(model=学生记录,form=modelform,extra=默认参数)
form_set_obj = modelformset_factory(model=models.StudentStudyRecord, form=StudyRecordDeialModelForm, extra=0)
# 通过创建的modelformset_factory创建的对象(queryset=学生记录对象)
formset = form_set_obj(queryset=all_study_recored)
return render(request, 'student/study_record_detail.html', {'formset': formset})
def post(self, request, class_record_id):
# 创建一个modelformset_factory对象(model=学生记录,form=modelform,extra=默认参数)
form_set_obj = modelformset_factory(model=models.StudentStudyRecord, form=StudyRecordDeialModelForm, extra=0)
# 对象中保存request.POST
formset = form_set_obj(request.POST)
# formset调用is_valid方法
if formset.is_valid():
# 保存formset.save方法
formset.save()
else:
# 否则打印错误信息
print(formset.errors)
# 重定向
# return redirect(reverse('study_record', args=(class_record_id,)))
return redirect(reverse("class_record"))
html文件:
注意:加上{{ formset.management_form }} 这句,固定格式写法
{% extends 'base.html' %} {# formset版本 #} {% block header %} <h1>学习记录详情!</h1> {% endblock header %} {% block content %} <section class="content"> <div class="row"> <div class="col-xs-12"> <div class="box"> <div class="box-header"> <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" class="btn btn-success" value="保存"> </form> </div> <!-- /.box-batch-manager --> </div> <!-- /.box --> </div> <!-- /.col --> </div> <!-- /.row --> </section> {{ ret_html|safe }} {% endblock content %}
https://www.cnblogs.com/WiseAdministrator/