Multi-Object-Edit With Django FormSets
I had to write a multi-object edit table the other day for a Django project and as such I dove into the FormSet Documentation. Django’s documentation is really good usually but the part abut the FormSets was a bit of a letdown.
So in case anybody else is in the same situation here is some code of how I did it (written from memory - should still be okay I hope).
# forms.py
from django import forms
from django.forms.models import modelformset_factory
# creating a FormSet for a specific Model is easy
FooFormSetBase = modelformset_factory(
Foo, extra=0, fields=('somefield', 'someotherfield'))
# now we want to add a checkbox so we can do stuff to only selected items
class FooFormSet(FooFormSetBase):
# this is where you can add additional fields to a ModelFormSet
# this is also where you can change stuff about the auto generated form
def add_fields(self, form, index):
super(FooFormSet, self).add_fields(form, index)
form.fields['is_checked'] = forms.BooleanField(required=False)
form.fields['somefield'].widget.attrs['class'] = 'somefieldclass'
After writing the FormSet itself here is the view:
# views.py
from django.shortcuts import redirect
from django.template import RequestContext
from fooproject.fooapp.forms import FooFormSet
from fooproject.models import Foo
def fooview(request):
if request.method == 'POST':
# we have multiple actions - save and delete in this case
action = request.POST.get('action')
formset = FooFormSet(
request.POST, queryset=Foo.objects.all())
if formset.is_valid():
# iterate over all forms in the formset
for form in formset.forms:
# only do stuff for forms in which is_checked is checked
if form.cleaned_data.get('is_checked'):
if action == u'delete':
# we need to call save to get an actual model but
# there is no need to hit the database hence the
# commit=False
model_instance = form.save(commit=False)
# now that we got a model we can delete it
model_instance.delete()
if action == u'save':
form.save()
redirect('someview')
else:
formset = FooFormSet(queryset=Foo.objects.all())
return render_to_response('sometemplate.html', {'formset': formset},
context_instance=RequestContext(request))
Now all that’s missing is the template:
<form action="." method="post" accept-charset="utf-8">
<table>
<thead>
<tr>
<th>is_checked</th>
<th>somefield</th>
<th>someotherfield</th>
</tr>
</thead>
<tbody>
{% for form in formset.forms %}
<tr>
<td>
{# don't forget about the id field #}
{{ form.id }}
{{ form.is_checked }}
</td>
<td>{{ form.somefield }}</td>
<td>{{ form.someotherfield }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<p>
{# and don't forget about the management form #}
{{ formset.management_form }}
{% csrf_token %}
<button type="submit" name="action" value="save">save</button>
<button type="submit" name="action" value="delete">delete</button>
</p>
</form>
Of course there is stuff still missing – you won’t see errors in your form for example. But you get the general idea.
Multi-Object-Edit With Django FormSets的更多相关文章
- Tutorial : Implementing Django Formsets
A step-by-step tutorial for setting up and testing a standard Django formset. I’ve noticed on #djang ...
- vscode打开django项目pylint提示has not "object" member
vscode 打开 django 项目提示 has not "object" member 是因为 Django 动态地将属性添加到所有模型类中,所以 ide 无法解析. 解决方案 ...
- 《Django By Example》第十章 中文 翻译 (个人学习,渣翻)
书籍出处:https://www.packtpub.com/web-development/django-example 原作者:Antonio Melé (译者注:翻译本章过程中几次想放弃,但是既然 ...
- Django的admin源码浅析和模仿
admin模块: admin提供了5种接口 list_display, 指定数据展示字段,不能放多对多字段
- django 模板视图,表单视图,各种视图
Generic editing views¶ The following views are described on this page and provide a foundation for e ...
- Django Class Based View
本节内容 一 Class Based View 基于类的视图 1. 类的视图 View 2. 类的视图 TemplateView 3. 类的视图 login_required解决方法 二 ...
- Awesome Django
Awesome Django If you find Awesome Django useful, please consider donating to help maintain it. ...
- Django文档阅读-Day2
Django文档阅读 - Day2 Writing your first Django app, part 1 You can tell Django is installed and which v ...
- Django – query not equal
The simpliest way to retrieve data from tables is take them all. To do this, you can write: 1 all_e ...
随机推荐
- Unity3D资源
1.ShareSDK 地址:https://github.com/MobClub/New-Unity-For-ShareSDK 文档:产品集成步骤 2.Protobuf https://github. ...
- 学到了林海峰,武沛齐讲的Day51 django+数据库
连不上,通过这一步解决 搞死了..辛苦但觉得值得 刷数据库 出问题 IDEA关联MySQL报错:Server returns invalid timezone. Go to ‘Advanced’ ta ...
- JS实现 Tab栏切换案例
要求:当鼠标点击上面相应的选项卡(tab),下面页面的内容也随之而改变. 结构分析: 全部的内容都放到一个大的盒子里面,盒子里面又可以分为上面和下面两个盒子. 上面的盒子放了 5个li,装着5个小的选 ...
- vue-upload 封装组件-上传组件
我后端的,刚接触vue个星期,根据需求写了个上传控件,很灵活的.没有看element el-upload源码,样式用的element的.感觉vue确实好用. 先看样子: <!-- 单文件上传组件 ...
- [模板] 计算几何2: 自适应Simpson/凸包/半平面交/旋转卡壳/闵可夫斯基和
一些基本的定义在这里: [模板] 计算几何1(基础): 点/向量/线/圆/多边形/其他运算 自适应Simpson Simpson's Rule: \[ \int ^b_a f(x)dx\approx ...
- 计蒜客 2018南京网络赛 I Skr ( 回文树 )
题目链接 题意 : 给出一个由数字组成的字符串.然后要你找出其所有本质不同的回文子串.然后将这些回文子串转化为整数后相加.问你最后的结果是多少.答案模 1e9+7 分析 : 应该可以算是回文树挺裸的题 ...
- codevs 5960 信使x
题目描述 Description •战争时期,前线有n个哨所,每个哨所可能会与其他若干个哨所之间有通信联系.信使负责在哨所之间传递信息,当然,这是要花费一定时间的(以天为单位).指挥部设在第一个哨所. ...
- springboot + mybatis sql日志
#mapper sql日志 替换成你的mapper接口所在的包名 logging.level.com.example.dao=debug
- HDU6579 Operation
题目链接 问题分析 区间求异或和最大,比较自然的想到了线性基.而每次求一个区间的线性基显然是行不通的.我们考虑在每个位置求出首位置到当前位置的线性基.同时我们要使线性基中高位的位置所选的数尽量靠后.这 ...
- AtCoder AGC032D Rotation Sort (DP)
题目链接 https://atcoder.jp/contests/agc032/tasks/agc032_d 题解 又是一道神仙题啊啊啊啊...atcoder题真的做不来啊QAQ 第一步又是神仙转化: ...