django中使用modelformset_factory批量修改数据

在python中viwes中写入

from django.forms.models import modelformset_factory#先导入modelformset
#创建一个modelform
class StudyrecordForm(forms.ModelForm):
    class Meta:
        model = models.StudyRecord
        fields='__all__'
#创建一个视图
def studyrecord(request,pk=None):
    if request.method == 'GET':
        formset_cls = modelformset_factory(model=models.StudyRecord, form=StudyrecordForm, extra=0)#这里面最少需要两个参数一个是model,一个是form组件,extra是多余出来的一行默认是一行,不需要可以写成0
        ret = models.StudyRecord.objects.filter(course_record_id=pk)
        formset = formset_cls(queryset=ret)
         #modelformset默认是将所有的数据帮你渲染,你可以通过queryset来过滤筛选条件
        return render(request,'saleshtml/studyrecord.html',{'formset':formset})
    else:
        formset_cls = modelformset_factory(model=models.StudyRecord, form=StudyrecordForm, extra=0)
        formset = formset_cls(request.POST)#post过来和modelform的用法是差不都的,一样要传request.POST
        if formset.is_valid():
            formset.save()
            return redirect(request.path)
        else:
            return render(request, 'saleshtml/studyrecord.html', {'formset': formset}) 

在前端模板中写入

 {{ formset.errors }}#这里是报错信息
    <form action="" method="post">
    {% csrf_token %}
    <table class="table table-bordered table-hover table-striped">
        <thead>
            <tr>
                <th><input type="checkbox" name="multiple"  value="{{ foo.id }}">序号</th>
                <th>考勤</th>
                <th>本节成绩</th>
                <th>作业批语</th>
                <th>某节课程</th>
                <th>学员</th>
            </tr>
        </thead>
        <tbody>
            {{ formset.management_form }}#一定要写这句话,这个是formset提交数据时的标记
            {% for foo in formset %}
                {{ foo.id }}#这个字段是提交时确定字段id的,在前端是看不到的,但一定要加上
                <tr class="text-center">
                    <td>{{ forloop.counter }}</td>
                    <td>{{ foo.attendance }}</td>
                    <td>{{ foo.score }}</td>
                    <td>{{ foo.homework_note }}</td>
                    <td>{{ foo.instance.course_record }}</td>#有些字段在前端展示的时候是不能让他修改的就可以用.instance来转成字符串
                    <td class="hidden">{{ foo.course_record }}</td>#但如果此字段还需要提交到后台的话,可以将他隐藏
                    <td>{{ foo.instance.student }}</td>
                    <td class="hidden">{{ foo.student }}</td>

                </tr>
            {% endfor %}

        </tbody>
    </table>
    <button class="btn btn-success">提交</button>
</form>

 

posted @ 2019-08-14 15:30  happy豪  阅读(379)  评论(0)    收藏  举报