crm录入成绩modelformset组件

不基于formset组件的普通写法>>

views:

class RecordScoreView(View):
    # 录入成绩
    def get(self, request,class_study_record_id):
        class_study_record_obj = ClassStudyRecord.objects.get(pk=class_study_record_id)

        student_study_record_list = class_study_record_obj.studentstudyrecord_set.all()
        score_choices = StudentStudyRecord.score_choices
        return render(request,"study_record/record_score.html",locals())

    def post(self, request, class_study_record_id):
        print(request.POST)
        data_dict = {}
        for key, val in request.POST.items():
            print(key, val)
            if key == "csrfmiddlewaretoken":
                continue # 跳过
            field, pk = key.rsplit("_", 1) # 切割 以右为分分一次
            if pk not in data_dict:

                data_dict[pk] = {
                    field: val
                }
            else:
                data_dict[pk][field] = val

        print(data_dict)
        for pk, data in data_dict.items():
            StudentStudyRecord.objects.filter(pk=pk).update(**data)
        #StudentStudyRecord.objects.filter(pk=pk).update(**{field:val}) 等同于field = val 打散的格式
        return redirect(reverse("class_study_record"))

html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>录入成绩</title>
    <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css">
</head>
<body>
    <h2 style="text-shadow: 4px 4px 4px rgba(10,21,49,0.72), 0px 0px 2px rgba(10,21,49,0.69);color:  #254e99">
        录入{{ class_study_record_obj.class_obj }},day{{ class_study_record_obj.day_num }}成绩
    </h2>
    <div class="container">
        <form action="" method="post">
            {% csrf_token %}
            <table class="table table-hover table-striped">
                <thead>
                    <tr>
                        <th>编号</th>
                        <th>姓名</th>
                        <th>考勤</th>
                        <th>成绩</th>
                        <th>批语</th>
                    </tr>
                </thead>
                <tbody>
                    {% for student_study_record in student_study_record_list %}
                        <tr>
                            <td>{{ forloop.counter }}</td>
                            <td>{{ student_study_record.student }}</td>
                            <td>{{ student_study_record.get_record_display }}</td>
                            <td>
                                <select name="score_{{ student_study_record.pk }}" id="">
                                  {% for score_choice in score_choices %}
                                      {% if student_study_record.score == score_choice.0 %}
                                            <!-- selected 预选中-->
                                            <option selected value="{{ score_choice.0 }}">{{ score_choice.1 }}</option>
                                      {% else %}
                                            <option value="{{ score_choice.0 }}">{{ score_choice.1 }}</option>
                                      {% endif %}
                                  {% endfor %}

                              </select>
                            </td>
                            <td>
                                <textarea name="homework_note_{{ student_study_record.pk }}" id="" cols="20" rows="1" class="form-control">{{ student_study_record.homework_note|default:"" }}</textarea>
                            </td>
                        </tr>
                    {% endfor %}
                </tbody>
            </table>
            <input type="submit" class="btn btn-success pull-right baocun" value="保存">
        </form>
    </div>
<script src="/static/AdminLTE-2.3.3/plugins/jQuery/jQuery-2.2.0.min.js"></script>
<script>
    $(function () {
        $(".baocun").click(function () {
            alert("保存成功!")
        })
    })
</script>
</body>
</html>
View Code

 

基于modelformset的写法>>

用modelformset首先得有一个modelform类

 

class StudentStudyRecordModelForm2(forms.ModelForm):
    class Meta:
        model=StudentStudyRecord
        # 需要编辑校验的字段,不编辑的不协商__all__所有字段
        fields=["score","homework_note"]

view:

引入modelformset

from django.forms.models import modelformset_factory

CBV 视图:

# 基于ModelFormSet 的录入成绩视图| 多个表单
class RecordScoreView2(View):

    def get(self, request,class_study_record_id):
        model_formset_cls = modelformset_factory(model=StudentStudyRecord, form=StudentStudyRecordModelForm2, extra=0) #extra=0设置额外增添的编辑表单个数
        queryset = StudentStudyRecord.objects.filter(classstudyrecord=class_study_record_id)

        # 把当前班级对象下面的所有学生学习记录对象传给ModelFormSet
        # formset每一条学生记录对象做成一个表单对象
        formset = model_formset_cls(queryset=queryset)
        return render(request,"study_record/record_score_formset.html",locals())

    def post(self, request,class_study_record_id):
        model_formset_cls = modelformset_factory(model=StudentStudyRecord, form=StudentStudyRecordModelForm2, 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(reverse("class_study_record"))

html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>录入成绩</title>
    <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css">
</head>
<body>
 <div class="panel panel-default">
        <div class="panel-heading">学习记录</div>
        <div class="panel-body">
            <div style="width: 680px;margin: 0 auto;">
                <form method="post" action="">
                    {% csrf_token %}
                    <!--用formset必须加这句话-->
                    {{ 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>
                                <!--instance 不编辑的字段,设置为原值不渲染-->
                                <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 pull-right baocun" value="保存">
                </form>
            </div>
        </div>
    </div>
<hr>
<script src="/static/AdminLTE-2.3.3/plugins/jQuery/jQuery-2.2.0.min.js"></script>
<script>
    $(function () {
        $(".baocun").click(function () {
            alert("保存成功!")
        })
    })
</script>
</body>
</html>

 

posted @ 2018-11-21 19:17  清风_Z  阅读(219)  评论(0编辑  收藏  举报