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 ...
 
随机推荐
- windows时钟服务设置
			
运行Regedit,打开注册表编辑器. 找到注册表项HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\Config\,将Anno ...
 - jdbc.properties不能加载到tomcat项目下面
			
javaweb项目的一个坑,每次重启tomcat都不能将项目中的jdbc.properties文件加载到tomcat项目对应的classes目录下面,得手动粘贴到该目录下.
 - 安装nodejs与使用
			
nodejs 官方下载地址:https://nodejs.org/en/ 下载完成后,双击打开安装程序 然后: 然后点击install,等待安装 安装完成后的目录如下: 检测是否真的安装成功.打开cm ...
 - 【leetcode】1274. Number of Ships in a Rectangle
			
题目如下: (This problem is an interactive problem.) On the sea represented by a cartesian plane, each sh ...
 - idea生成实体类
			
1.点击View->Tool Windows->Database 2.点击Datebase框的加号,DateSource,选择对应的数据源,配置对应信息,点击Test Connection ...
 - Nowcoder Monotonic Matrix ( Lindström–Gessel–Viennot lemma 定理 )
			
题目链接 题意 : 在一个 n * m 的矩阵中放置 {0, 1, 2} 这三个数字.要求 每个元素 A(i, j) <= A(i+1, j) && A(i, j) <= ...
 - SSM框架搭建,以及mybatis学习
			
前两天在研究SSM框架,然后看到一篇博文,写的很清晰,照着实现了一下,这里就不重复写了,把博文地址留一下 http://blog.csdn.net/zhshulin/article/details/3 ...
 - [CSP-S模拟测试]:五子棋(模拟)
			
题目传送门(内部题122) 输入格式 输入文件第一行为一个正整数$n$,表示双方总共下了多少步棋. 接下来$n$行,输入文件每行两个正整数.第$i$行的两个数$x,y$表示第$i$步的棋子下在了第$x ...
 - 利用MFC在控件内将txt中的数据画图
			
1:采集txt文件中的数据测试程序如下: #include "stdafx.h" #include <fstream> #include "iostream& ...
 - spring的AOP基本原理
			
一.什么是AOP AOP(Aspect Oriented Programming),意思是面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术.AOP基于IoC基础,是对OOP ...