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. python+openCV实现双目视差图及测距

    通过matlab标定得到相机参数放到stereoconfig.py import numpy as np import cv2 #双目相机参数 class stereoCameral(object): ...

  2. 我说CMMI之四:CMMI的表示方法--转载

    版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明.本文链接:https://blog.csdn.net/dylanren/article/deta ...

  3. 关于css阴影和浮动

    盒子阴影box-shadow box-shadow:0 0 1px #000 inset; 水平  垂直   模糊  颜色 : [1] inset代表框内阴影,不加inset代表框外阴影 [2]第1个 ...

  4. ${filename}用法一:${file内部的#%的匹配方式}

    假设我们定义了一个变量为: file=/dir1/dir2/dir3/my.file.txt 我们可以用${ }分别替换获得不同的值: ${file#*/}:拿掉第一条/及其左边的字串:dir1/di ...

  5. hiho #1043 : 完全背包

    01背包和完全背包解析 在上一节的01背包中,每种物品只能使用一次. 初始化j=V,逆序推能够保证 dp[v-c[i]] 保存的是状态是 dp[i-1][v-c[i]] ,也就是每个物品只被使用了一次 ...

  6. 什么是IoC和DI?DI是如何实现的?

    IoC叫控制反转,是Inversion of Control的缩写,控制反转是把传统上由程序代码直接操控的对象的调用权交给容器,通过容器来实现对象组件的装配和管理.所谓的"控制反转" ...

  7. Linux 查看内存条数据和大小命令

    查看内存条数据和大小命令: sudo dmidecode | grep -A16 "Memory Device$" 需要root 权限.. [life@localhost mp3b ...

  8. Idea 设置maven配置文件settings.xml的位置

    1.[File] >  [Other Settings] > [Default Settings] 2.设置 settings.xml 配置 本博文来源于:https://blog.csd ...

  9. jpa repostiory

    JpaRepository的查询   image.png   image.png Spring Data JPA框架在进行方法名解析时,会先把方法名多余的前缀截取掉,比如 find.findBy.re ...

  10. python中的实例方法、类方法、静态方法的区别

    Python 除了拥有实例方法外,还拥有静态方法和类方法,跟Java相比需要理解这个类方法的含义. class Foo(object): def test(self)://定义了实例方法 print( ...