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 ...
随机推荐
- HDU - 6589 Sequence (生成函数+NTT)
题目链接 设序列a的生成函数$\large f(x)=\sum\limits_{i=0}^{n-1}a_ix^i$,则操作1,2,3分别对应将$f(x)$乘上$\Large\frac{1}{1-x}, ...
- 用Python实现九九乘法表打印
#!usr/bin/env python # -*- coding:utf-8 -*- # dic={ # 'apple':10, # 'iphon':5000, # 'wwatch Tv':3000 ...
- LightOJ-1104-birthday Paradox(概率)
链接: https://vjudge.net/problem/LightOJ-1104 题意: Sometimes some mathematical results are hard to beli ...
- 【转】推荐几本学习MySQL的好书-MySQL 深入的书籍
MySQL的使用 1 MySQL技术内幕InnoDB存储引擎 2 MySQL的官方手册 3 MySQL排错指南 4 高性能MySQL 5 数据库索引设计与优化 6 Effective MySQL系列 ...
- javascript / angular 如何把object转成array
取出的api 格式是纯object格式 {"name":"james","city":"Taipei","co ...
- Java中接口与抽象类的异同
定义(以下是百度百科中的定义): Java接口:Java接口是一系列方法的声明,是一些方法特征的集合,一个接口只有方法的特征没有方法的实现,因此这些方法可以在不同的地方被不同的类实现,而这些实现可以具 ...
- Visual Stdio C++ 编译器、链接器常用命令
概览: cmd常用命令配合使用: del 删除指定文件 同erase cls 清屏 rd 删除空目录文件夹 dir 显示目录 cd 在当前盘符跳转指定目录(不同盘符跳转用盘符号)(分别表示根目录 上一 ...
- sklearn可实现的函数或者功能可分为如下几个方面
1.分类算法2.回归算法3.聚类算法4.降维算法5.模型优化6.文本预处理 其中分类算法和回归算法又叫监督学习,聚类算法和降维算法又叫非监督学习 分类算法 1 2 3 4 5 6 7 8 9 10 1 ...
- [Pytorch笔记] scatter_
https://blog.csdn.net/qq_16234613/article/details/79827006 scatter_(input, dim, index, src)将src中数据根据 ...
- python 学习之路(1)
1变量的使用以及原理 先定义一个变量 变量的类型 变量的命名 01变量的命名 变量名 = 值 左边是变量名 右边是值 又叫做赋值 上面是ipython的交互模式的 那我们看看在pycharm里面如何输 ...