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 ...
随机推荐
- MHA介绍和基础、原理、架构、工具介绍
一.MHA简介 软件简介 MHA(Master High Availability)目前在MySQL高可用方面是一个相对成熟的解决方案,它由日本DeNA公司youshimaton(现就职于Facebo ...
- 多对多第三张表的创建方式 和 forms组件的使用
目录 一.多对多第三张表的创建 1. 全自动方式 (1)实现代码 (2)优点和不足 2. 纯手撸方式(了解) (1)实现代码 (2)优点和不足 3. 半自动方式(推荐使用) (1)实现代码 (2)优点 ...
- 在vue2.0中使用bootstarpTable(jquery+bootstarp+bootstarpTable)
要想使用bootstarp-table就需要按顺序引入 jquery > bootstarp > bootstarp-table //路径可能会有变动 最好在node_modules ...
- DOM修改
㈠DOM标准 核心DOM: HTML DOM ...
- poj 3684 Physics Experiment 弹性碰撞
Physics Experiment Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 1489 Accepted: 509 ...
- tarjan算法 习题
dfs树与tarjan算法 标签(空格分隔): 517coding problem solution dfs树 tarjan Task 1 给出一幅无向图\(G\),在其中给出一个dfs树\(T\), ...
- HGOI 20190708 题解
Problem A 拿出勇气吧 幸运数字每一位是$4$或者$7$,现在给出一个数字每位数位上数的和为n,求出最小的幸运数n 对于100%的数据,$n\leq 10^6$ Sol : 显然本题要求数的长 ...
- TCP序列号和确认号
TCP序列号和确认号详解 在网络分析中,读懂TCP序列号和确认号在的变化趋势,可以帮助我们学习TCP协议以及排查通讯故障,如通过查看序列号和确认号可以确定数据传输是否乱序.但我在查阅了当前很多资料后发 ...
- python爬取智联招聘职位信息(多进程)
测试了下,采用单进程爬取5000条数据大概需要22分钟,速度太慢了点.我们把脚本改进下,采用多进程. 首先获取所有要爬取的URL,在这里不建议使用集合,字典或列表的数据类型来保存这些URL,因为数据量 ...
- 「SCOI2015」小凸玩矩阵
题目链接 问题分析 题目给了充足的暗示,我们只需要二分答案然后跑匈牙利即可.要相信匈牙利的速度 参考程序 #include <bits/stdc++.h> using namespace ...