Similar to the regular formsets, Django also provides model formset that makes it easy to work with Django models. Django model formsets provide a way to edit or create multiple model instances within a single form. Model Formsets are created by a factory method. The default factory method is modelformset_factory(). It wraps formset factory to model forms. We can also create inlineformset_factory() to edit related objects. inlineformset_factory wraps modelformset_factory to restrict the queryset and set the initial data to the instance’s related objects.

Step1: Create model in models.py

class User(models.Model):
    first_name = models.CharField(max_length=150)
last_name = models.CharField(max_length=150)
  user_group = models.ForeignKey(Group)
    birth_date = models.DateField(blank=True, null=True)

Step2: in forms.py

from django.forms.models import modelformset_factory
from myapp.models import User UserFormSet = modelformset_factory(User, exclude=())

This will create formset which is capable of working with data associated with User model. We can also pass the queryset data to model formset so that it can do the changes to the given queryset only.

formset = UserFormSet(queryset=User.objects.filter(first_name__startswith='M'))

We can produce an extra form in the template by passing 'extra' argument to the modelformset_factory method, we can use this as follows.

UserFormSet = modelformset_factory(User, exclude=(), extra=1)

We can customize the form that will be displayed in the template by passing the new customized form to modelformset_factory. For eg: in our current example if want birth_date as date picker widget then we can achieve this with the following change in our forms.py.

class UserForm(forms.ModelForm):

    birth_date = forms.DateField(widget=DateTimePicker(options={"format": "YYYY-MM-DD", "pickSeconds": False}))
class Meta:
model = User
exclude = () UserFormSet = modelformset_factory(User, form=UserForm)

In general Django's model formsets do validation when at least one from data is filled, in most of the cases there we'll be needing a scenario where we require at least one object data to be added or another scenario where we'd be required to pass some initial data to form, we can achieve this kind of cases by overriding basemodelformset as following,

in forms.py

class UserForm(forms.ModelForm):

    birth_date = forms.DateField(widget=DateTimePicker(options={"format": "YYYY-MM-DD", "pickSeconds": False}))
class Meta:
model = User
exclude = () def __init__(self, *args, **kwargs):
self.businessprofile_id = kwargs.pop('businessprofile_id')
super(UserForm, self).__init__(*args, **kwargs) self.fields['user_group'].queryset = Group.objects.filter(business_profile_id = self.businessprofile_id) BaseUserFormSet = modelformset_factory(User, form=UserForm, extra=1, can_delete=True) class UserFormSet(BaseUserFormSet): def __init__(self, *args, **kwargs):
# create a user attribute and take it out from kwargs
# so it doesn't messes up with the other formset kwargs
self.businessprofile_id = kwargs.pop('businessprofile_id')
super(UserFormSet, self).__init__(*args, **kwargs)
for form in self.forms:
form.empty_permitted = False def _construct_form(self, *args, **kwargs):
# inject user in each form on the formset
kwargs['businessprofile_id'] = self.businessprofile_id
return super(UserFormSet, self)._construct_form(*args, **kwargs)

Step3:  in views.py

from myapp.forms import UserFormSet
from django.shortcuts import render_to_response def manage_users(request):     if request.method == 'POST':
        formset = UserFormSet(businessprofile_id=businessprofileid, data=request.POST)
        if formset.is_valid():
            formset.save()
            # do something
    else:
        formset = UserFormSet(businessprofile_id=businessprofileid)
    return render_to_response("manage_users.html", {"formset": formset})

Step4: in template

The simplest way to render your formset is as follows.

       <form method="post" action="">
             {{ formset }}
      </form>

DJANGO MODEL FORMSETS IN DETAIL AND THEIR ADVANCED USAGE的更多相关文章

  1. Django model总结(上)

    Django model是django框架中处于比较核心的一个部位,准备分三个博客从不同的方面分别进行阐述,本文为<上篇>,主要对[a]Model的基本流程,比如它的创建,迁移等:默认行为 ...

  2. 【转】Django Model field reference学习总结

    Django Model field reference学习总结(一) 本文档包含所有字段选项(field options)的内部细节和Django已经提供的field types. Field 选项 ...

  3. Django model字段类型清单

    转载:<Django model字段类型清单> Django 通过 models 实现数据库的创建.修改.删除等操作,本文为模型中一般常用的类型的清单,便于查询和使用: AutoField ...

  4. Django:Model的Filter

    转自:http://www.douban.com/note/301166150/   django model filter 条件过滤,及多表连接查询.反向查询,某字段的distinct   1.多表 ...

  5. Django model中 双向关联问题,求帮助

    Django model中 双向关联问题,求帮助 - 开源中国社区 Django model中 双向关联问题,求帮助

  6. django 自定用户系统 以及 Django Model 定义语法

    http://www.tuicool.com/articles/jMzIr2 django使用自己的用户系统 http://www.jianshu.com/p/c10be59aad7a Django ...

  7. tornado with MySQL, torndb, django model, SQLAlchemy ==> JSON dumped

    现在,我们用torndo做web开发框架,用他内部机制来处理HTTP请求.传说中的非阻塞式服务. 整来整去,可谓之一波三折.可是,无论怎么样,算是被我做成功了. 在tornado服务上,采用三种数据库 ...

  8. Django Model field reference

    ===================== Model field reference ===================== .. module:: django.db.models.field ...

  9. Django model对象接口

    Django model查询 # 直接获取表对应字段的值,列表嵌元组形式返回 Entry.objects.values_list('id', 'headline') #<QuerySet [(1 ...

随机推荐

  1. 第二章 Vue快速入门-- 16 vue中通过属性绑定为元素绑定style行内样式

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8&quo ...

  2. GlusterFS 分布式文件系统

    简介 官方文档:https://docs.gluster.org/en/latest/Quick-Start-Guide/Architecture/ Glusterfs是一个开源的分布式文件系统,是S ...

  3. 我所亲身经历的CMMI3 [问题点数:20分,结帖人outer2000]--转载

    很荣幸,作为某公司软件部门的软件项目经理,亲身经历了CMMI3,以下就把整个改进过程,用自己的亲身体会,详述如下,文中一些观点与看法难免带有个人感情,还请各位酌情参考. 公司情况简单介绍下,因为是为某 ...

  4. IT项目开发流程

    项目开发流程: 一.需求分析:相关系统分析员向用户初步了解需求,然后用相关的工具软件列出要开发的系统的大功能模块,每个大功能模块有哪些小功能模块,对于有些需求比较明确相关的界面时,在这一步里面可以初步 ...

  5. Newsgroups数据集研究

    1.数据集介绍 20newsgroups数据集是用于文本分类.文本挖据和信息检索研究的国际标准数据集之一. 数据集收集了大约20,000左右的新闻组文档,均匀分为20个不同主题的新闻组集合. 一些新闻 ...

  6. 《剑指offer》算法题第四天

    今日题目: 二进制中1的个数 数值的整数次方 调整数组顺序使奇数位于偶数前面 链表中倒数第K个节点 链表中环的入口节点 今天的题目都比较简单,但是前三道题都有不同的解法,4,5两题就不在这边讨论了,其 ...

  7. ELEMENT-UI 封装el-table 局部刷新row

    //关于封装的el-table行数据更新后如何局部更新row row.status=status; this.$set(this.$refs.elTable.$data.tableData,index ...

  8. H5+JAVA的文件上传,断点续传

    这里只写后端的代码,基本的思想就是,前端将文件分片,然后每次访问上传接口的时候,向后端传入参数:当前为第几块文件,和分片总数 下面直接贴代码吧,一些难懂的我大部分都加上注释了: 上传文件实体类: 看得 ...

  9. Java 工程师成神之路

    基础篇 → 什么是面向对象 面向对象.面向过程 是一种新兴的程序设计方法,或者是一种新的程序设计规范(paradigm),其基本思想是使用对象.类.继承.封装.多态等基本概念来进行程序设计.从现实世界 ...

  10. [CSP-S模拟测试]:求和(数学)

    题目传送门(内部题107) 输入格式 一行五个正整数$x_1,y_1,x_2,y_2,m$ 输出格式 输出一个整数,为所求的答案对$m$取模后的结果. 样例 样例输入: 2 1 5 3 10007 样 ...