• Django组件之modelformset


    ModelFormSet 基于modelform 实现的批量处理

    前端:

    <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>

    在前端中使用的时候需要注意:  {{ formset.management_form }} 这行代码必须加入。

    视图与form:

    from django.forms.models import modelformset_factory
    
    
    class StudentStudyRecordModelForm(forms.ModelForm):
        class Meta:
            model=StudentStudyRecord
            fields=["score","homework_note"]
    
    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)

    也就是说使用时需注意 modelformset_factory()中有两个参数必须给值,model绑定的是模型表,form绑定的是与之相关的modelform,

  • 相关阅读:
    最大回文子串
    找出不含重复字符的最长子串的长度
    链表表示的2个数相加
    如何胜任一个小型公司的技术总监?我的感想
    React 的坑
    MobX 学习
    摘要
    AI 帮助涂鸦
    计算机的前世今生
    常用编辑器实用技巧(pycharm、sublimeText、vim、vscode、Jupyter)
  • 原文地址:https://www.cnblogs.com/qq631243523/p/9989392.html
Copyright © 2020-2023  润新知