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. VMware Tools按钮变灰色,无法安装的解决方法

    参考博客: https://blog.csdn.net/weixin_30639719/article/details/94846851 https://jingyan.baidu.com/artic ...

  2. 第二章 Vue快速入门-- 28 自定义按键修饰符

    事件处理-按键修饰符 js 里面的键盘事件对应的键码 <!DOCTYPE html> <html lang="en"> <head> <m ...

  3. 前端面试题-CSS优先级

    一.选择器优先级 浏览器通过优先级来判断哪一些属性值与一个元素最为相关,从而在该元素上应用这些属性值.优先级是基于不同种类选择器组成的匹配规则. 二.优先级计算 优先级就是分配给指定的CSS声明的一个 ...

  4. thinkphp5权限仿制

    权限列表 流程 thinkphp5封装好的权限模块 RBAC还有auth and then .......管理员表,可以依据auth.php搭建所有的权限表

  5. CMD命令行基本命令

    基本知识 输入 功能 Alt+Enter 全屏 Ctrl+S 暂停输出 Ctrl+C Ctrl+Break 停止程序 Ctrl+Z 表示输入结束 <file 从文件读标准输入 >file ...

  6. Eclipse 开发环境修改及MAVEN配置

    Eclipse集成Maven配置 默认为 修改为所用版本 选择maven软件所在目录 勾选 默认连接仓库为 修改为

  7. 计蒜客T2202 数三角形(提高组2017模拟赛(三)day2T3) LZOJ3878攻略

    今天模拟赛考了一道计蒜客NOIP2017模拟赛(三)day2T3的数三角形,原题链接 https://nanti.jisuanke.com/t/T2202 ,LZOJ3878攻略.场上想了很久都没转化 ...

  8. C语言写数据库(三)

    遇到的问题以及解决思路方法 1.外部导入数据库文件 进入mysql,创建数据库sh_robot source /home/exbot/sh_robot.sql 查看数据库编码格式 show varia ...

  9. 【Python】PIL模块

    Python自建库,在爬虫等基础应用中更加简单好记,做整理以备自查. 目录 Image模块 open类.Save类.format类.Mode类.convert类.Size类.Info类.new类.Co ...

  10. JAVASCRIPT试题及答案

    1.用jQuery编程实现获取选中复选框值的函数abc. <body> <input type="checkbox" name="aa" va ...