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,

最新文章

  1. svn清除已保存的用户名和密码
  2. Django表单验证
  3. fzuoj Problem 2179 chriswho
  4. 由ccf第一题引出的问题
  5. Redis缓存服务搭建及实现数据读写
  6. Memcached学习(三)
  7. 集合(Collection,set,list,map)
  8. Scala函数字面量简化写法
  9. ACE 容器之三 ACE_Unbounded_Queue的使用
  10. Servlet.service() for Servlet jsp threw exception javax.servlet.ServletException:File &amp;quot;/pageFoo
  11. LIRe 源代码分析 5:提取特征向量[以颜色布局为例]
  12. Python调用ansible API系列(五)综合使用
  13. hdu 1052 Tian Ji -- The Horse Racing【田忌赛马】
  14. mongodb安装和运行
  15. 算法:60.第k个排列
  16. Eclipse GBK批量转UTF-8插件(转)
  17. sql 创建数据语句
  18. Django models 的常用字段类型和字段参数
  19. Elon Musk
  20. Codeforces Round #358 (Div. 2) C. Alyona and the Tree 水题

热门文章

  1. PAT 甲级 1065 A+B and C (64bit) (20 分)(溢出判断)*
  2. Uncaught TypeError: TableInit is not a constructor
  3. 【C/C++开发】C中调用C++函数
  4. Dotmemory 内存分析工具的操作手册
  5. Clean Code 代码检查清单
  6. 转录组组装软件stringtie
  7. Python 机器学习库 NumPy 教程
  8. STL源码剖析——空间配置器Allocator#1 构造与析构
  9. 剑指offer61:序列化二叉树
  10. centos7安装oracle11g(根据oracle官方文档安装,解决图形界面安装问题)