DJANGO MODEL FORMSETS IN DETAIL AND THEIR ADVANCED USAGE
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的更多相关文章
- Django model总结(上)
Django model是django框架中处于比较核心的一个部位,准备分三个博客从不同的方面分别进行阐述,本文为<上篇>,主要对[a]Model的基本流程,比如它的创建,迁移等:默认行为 ...
- 【转】Django Model field reference学习总结
Django Model field reference学习总结(一) 本文档包含所有字段选项(field options)的内部细节和Django已经提供的field types. Field 选项 ...
- Django model字段类型清单
转载:<Django model字段类型清单> Django 通过 models 实现数据库的创建.修改.删除等操作,本文为模型中一般常用的类型的清单,便于查询和使用: AutoField ...
- Django:Model的Filter
转自:http://www.douban.com/note/301166150/ django model filter 条件过滤,及多表连接查询.反向查询,某字段的distinct 1.多表 ...
- Django model中 双向关联问题,求帮助
Django model中 双向关联问题,求帮助 - 开源中国社区 Django model中 双向关联问题,求帮助
- django 自定用户系统 以及 Django Model 定义语法
http://www.tuicool.com/articles/jMzIr2 django使用自己的用户系统 http://www.jianshu.com/p/c10be59aad7a Django ...
- tornado with MySQL, torndb, django model, SQLAlchemy ==> JSON dumped
现在,我们用torndo做web开发框架,用他内部机制来处理HTTP请求.传说中的非阻塞式服务. 整来整去,可谓之一波三折.可是,无论怎么样,算是被我做成功了. 在tornado服务上,采用三种数据库 ...
- Django Model field reference
===================== Model field reference ===================== .. module:: django.db.models.field ...
- Django model对象接口
Django model查询 # 直接获取表对应字段的值,列表嵌元组形式返回 Entry.objects.values_list('id', 'headline') #<QuerySet [(1 ...
随机推荐
- 【BZOJ3534】【Luogu P3317】 [SDOI2014]重建 变元矩阵树,高斯消元
题解看这里,主要想说一下以前没见过的变元矩阵树还有前几个题见到的几个小细节. 邻接矩阵是可以带权值的.求所有生成树边权和的时候我们有一个基尔霍夫矩阵,是度数矩阵减去邻接矩阵.而所谓变元矩阵树实际上就是 ...
- 阅读之Java多线程
Java多线程 用多线程只有一个目的,就是更好的利用cpu的资源,因为所有的多线程代码都可以用单线程来实现. 多线程:指的是这个程序(一个进程)运行时产生了不止一个线程 并行与并发: 并行:多个cpu ...
- Redis——SpringBoot项目使用Lettuce和Jedis接入Redis集群
Jedis连接Redis: 非线程安全 如果是多线程环境下共用一个Jedis连接池,会产生线程安全问题,可以通过创建多个Jedis实例来解决,但是创建许多socket会影响性能,因此好一点的方法是使用 ...
- 【leetcode】1187. Make Array Strictly Increasing
题目如下: Given two integer arrays arr1 and arr2, return the minimum number of operations (possibly zero ...
- docker 部署项目
一:我使用的是阿里云的ubuntu16.4系统. 项目数据库: # 数据源 spring: datasource: type: com.zaxxer.hikari.HikariDataSource d ...
- sublime text 编辑器的操作
我一直在用的代码编辑器是sublime text,然后总结了一些相关的操作方法. 一 环境操作 1.放大显示比例:Ctrl+ 2.缩小显示比例:Ctrl- 3.分屏:Alt+ Shift +数字 ...
- jquery checkbox选择器 语法
jquery checkbox选择器 语法 作用::checkbox 选择器选取类型为 checkbox 的 <input> 元素.大理石平台价格表 语法:$(":checkbo ...
- idea 导入(非maven)web项目并发布到tomcat服务器
IDEA 2017.1版本 web项目导入并发布到Tomcat服务器 1.点击编辑项目结构 2.点击project 将项目编译输出目录改成{项目目录}/OUT,并设置项目环境,编译版本 3.点击mod ...
- Js文件函数中调用另一个Js文件函数的方法
在项目中Js文件需要完成某一功能,但这一功能的大部分代码在另外一个Js文件已经完成,只需要调用这个文件实现功能.那么如何调用:一个Js文件函数中调用另一个Js文件函数的方法? (直接代码说明) 示例d ...
- Linux命令-文件管理(二)
Linux命令-文件管理(二) Linux gitview命令 Linux gitview命令用于观看文件的内容,它会同时显示十六进制和ASCII格式的字码. 语法:gitview [-bchilv] ...