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的更多相关文章

  1. Tutorial : Implementing Django Formsets

    A step-by-step tutorial for setting up and testing a standard Django formset. I’ve noticed on #djang ...

  2. vscode打开django项目pylint提示has not "object" member

    vscode 打开 django 项目提示 has not "object" member 是因为 Django 动态地将属性添加到所有模型类中,所以 ide 无法解析. 解决方案 ...

  3. 《Django By Example》第十章 中文 翻译 (个人学习,渣翻)

    书籍出处:https://www.packtpub.com/web-development/django-example 原作者:Antonio Melé (译者注:翻译本章过程中几次想放弃,但是既然 ...

  4. Django的admin源码浅析和模仿

    admin模块: admin提供了5种接口 list_display, 指定数据展示字段,不能放多对多字段

  5. django 模板视图,表单视图,各种视图

    Generic editing views¶ The following views are described on this page and provide a foundation for e ...

  6. Django Class Based View

    本节内容 一   Class Based View 基于类的视图 1.  类的视图 View 2.  类的视图 TemplateView 3.  类的视图 login_required解决方法 二   ...

  7. Awesome Django

     Awesome Django    If you find Awesome Django useful, please consider donating to help maintain it. ...

  8. Django文档阅读-Day2

    Django文档阅读 - Day2 Writing your first Django app, part 1 You can tell Django is installed and which v ...

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

随机推荐

  1. Android编程使用httpHelper不执行错误-20171017

    解决方法:将显示等代码(例如setText()和setAdapter()等方法)从主函数onCreate()中移到httpHelper.get()函数中:   原因:有可能是主线程运行的较快,而连接服 ...

  2. 最近老是有兄弟问我,Vue双向绑定的原理,以及简单的原生js写出来实现,我就来一个最简单的双向绑定,原生十行代码让你看懂原理

    废话不多说直接看效果图 代码很好理解,但是在看代码之前需要知道Vue双向绑定的原理其实就是基于Object.defineProperty 实现的双向绑定 官方传送门 这里我们用官方的话来说Object ...

  3. linux下使用 TC 对服务器进行流量控制

    tc 介绍 在linux中,tc 有二种控制方法 CBQ 和 HTB.HTB 是设计用来替换 CBQ 的.HTB比CBQ更加灵活,但是CPU 开销也更大,通常高速的链路会使用CBQ,一般而言HTB使用 ...

  4. 树莓派GPIO接口

    一.GPIO模式 GPIO分为板上模式和BCM模式 板上模式即为平时百度谷歌搜到的图,按顺序1-40排列(1B是26引脚) BCM模式为CPU分的,在图上一般会单独标记 二.引脚分类 1.电源:3.3 ...

  5. HTML DOM 事件与方法

    HTML DOM 事件允许Javascript在HTML文档元素中注册不同事件处理程序. 事件通常与函数结合使用,函数不会在事件发生前被执行! (如用户点击按钮). 鼠标事件 键盘事件 框架/对象(F ...

  6. Python 创建数据库表

    创建数据库表 如果数据库连接存在我们可以使用execute()方法来为数据库创建表,如下所示创建表EMPLOYEE: #!/usr/bin/python # -*- coding: UTF-8 -*- ...

  7. 翻页的时候更改URL地址

    要求点击第一页是url+p1html,点击第二页是url+p2html等等 $("body").on('click','#w_tagPage a[wid]',function(){ ...

  8. 【BZOJ3545&BZOJ3551】Peaks(kruskal重构树,主席树,dfs序)

    题意:在Bytemountains有N座山峰,每座山峰有他的高度h_i. 有些山峰之间有双向道路相连,共M条路径,每条路径有一个困难值,这个值越大表示越难走, 现在有Q组询问,每组询问询问从点v开始只 ...

  9. oracle(转)

    Oracle数据库基本操作 1.概述 Oracle数据库客户端一般需要安装在服务器上,可以在服务器端操作,一般我们可以用sql developer工具远程连接到数据库,先行建立数据库,然后对表进行增删 ...

  10. 导数与微分简单总结(updated)

    只讲一些导数在OI中的简单应用,特别基础的东西,不会很详细也不会很全面. 导数的定义 设函数\(y=f(x)\)在点\(x_0\)的某个邻域内有定义,当自变量\(x\)在\(x_0\)处有增量\(Δx ...