Django组件之modelformset
2024-08-26 23:03:32
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,
最新文章
- svn清除已保存的用户名和密码
- Django表单验证
- fzuoj Problem 2179 chriswho
- 由ccf第一题引出的问题
- Redis缓存服务搭建及实现数据读写
- Memcached学习(三)
- 集合(Collection,set,list,map)
- Scala函数字面量简化写法
- ACE 容器之三 ACE_Unbounded_Queue的使用
- Servlet.service() for Servlet jsp threw exception javax.servlet.ServletException:File &;quot;/pageFoo
- LIRe 源代码分析 5:提取特征向量[以颜色布局为例]
- Python调用ansible API系列(五)综合使用
- hdu 1052 Tian Ji -- The Horse Racing【田忌赛马】
- mongodb安装和运行
- 算法:60.第k个排列
- Eclipse GBK批量转UTF-8插件(转)
- sql 创建数据语句
- Django models 的常用字段类型和字段参数
- Elon Musk
- Codeforces Round #358 (Div. 2) C. Alyona and the Tree 水题
热门文章
- PAT 甲级 1065 A+B and C (64bit) (20 分)(溢出判断)*
- Uncaught TypeError: TableInit is not a constructor
- 【C/C++开发】C中调用C++函数
- Dotmemory 内存分析工具的操作手册
- Clean Code 代码检查清单
- 转录组组装软件stringtie
- Python 机器学习库 NumPy 教程
- STL源码剖析——空间配置器Allocator#1 构造与析构
- 剑指offer61:序列化二叉树
- centos7安装oracle11g(根据oracle官方文档安装,解决图形界面安装问题)