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+magicbox响应式风格)

    1.用脚手架初始化一个vue项目swain $ vue create swain 2.安装几个常用插件

  2. 【洛谷P2147】洞穴勘测

    题目大意:维护 N 个点的无向图,支持动态加边和删边,回答两点的连通性. 题解:线段树分治 + 可撤销并查集 询问可以离线,这是线段树分治的基础. 建立在操作时间轴上的线段树称为线段树分治算法. 本题 ...

  3. PHP preg_match正则表达式

    行定位符 ^表示开始 $表示结束 preg_match(模式,待搜索的字符串,$matches) 其中matches为可选参数,一旦匹配上,可以返回匹配结果 举个例子: $pattern = '/#\ ...

  4. IPC 进程间通信方式——消息队列

    消息队列 消息队列是内核中的一个链表 用户进程将数据传输到内核后,内核重新添加一些如用户ID.组ID.读写进程的ID和优先级等相关信息后并打包成一个数据包称为消息 允许一个或多个进程往消息队列中读写消 ...

  5. [人物存档]【AI少女】【捏脸数据】1224今日份的推荐

    点击下载(城通网盘):AISChaF_20191111222714074.png 点击下载(城通网盘):AISChaF_20191108141610951.png

  6. k8s-in-aciton-3

    镜像构建过程 构建过程不是由Docker客户端进行的,而是将整个目录的文件上传到Docker守护进程并在那里进行的.Docker客户端和守护进程不要求在同一 台机器上.如果你在一台非Linux操作系统 ...

  7. spring cloud禁止输出日志:ConfigClusterResolver : Resolving eureka endpoints via configuration

    springcloud的注册中心客户端会每隔一定时间向注册中心服务端发送心跳,用此来判断注册中心服务端是否运行正常. 这样导致不断进行日志输出,不便查看正常的业务日志输出. c.n.d.s.r.aws ...

  8. BZOJ 3173: [Tjoi2013]最长上升子序列 Splay

    一眼切~ 重点是按照 $1$~$n$ 的顺序插入每一个数,这样的话就简单了. #include <cstdio> #include <algorithm> #define N ...

  9. 2018中国大学生程序设计竞赛 - 网络选拔赛 Find Integer

    Find Integer Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others) Tot ...

  10. jpa repostiory

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