Django之ModelFormSet

ModelFormSet

批量增加

views

先定义一个普通的
class StudyRecordForm(BSForm):
    class Meta:
        model = models.StudyRecord
        fields ='__all__'


from django.forms import modelformset_factory     # 导入模块
def study_record(request,course_record_id):
    FormSet = modelformset_factory(model=models.StudyRecord,form=StudyRecordForm,extra=0)    # extra 格外生成选项,设置为0则不在出现
    formset_obj = FormSet(queryset=models.StudyRecord.objects.filter(course_record_id =course_record_id ))
    if request.method=='POST':
        formset_obj =FormSet(data=request.POST) 
        print(1111)
        if formset_obj.is_valid():
            formset_obj.save()
            print(222)
            next =request.GET.get('next')
            return redirect(next)

    return render(request,'teacher/study_record.html',{'formset_obj':formset_obj})

 

 

html

{{ formset_obj.management_form }}    #固定写法

{% for field in formset_obj %}
<tr>
{{ field.id }}                     # 固定写法
    <td>{{ forloop.counter }}</td>
    <td>{{ field.instance.student }}</td>   # 默认值加instance但不可选
    <td>{{ field.attendance }}</td>
    <td>{{ field.score }}</td>
    <td>{{ field.homework_note }}</td>
    <td class="hidden">{{ field.course_record }}</td> # hidden不显示但存在
    <td class="hidden">{{ field.student }}</td>
</tr>
{% endfor %}

 展现部分数据

 

posted @ 2019-09-23 22:58  驰念  阅读(307)  评论(0编辑  收藏  举报