博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
DJANGO MODEL FORMSETS IN DETAIL AND THEIR ADVANCED USAGE
阅读量:6282 次
发布时间:2019-06-22

本文共 3959 字,大约阅读时间需要 13 分钟。

Similar to the regular formsets,  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.

       
{ { formset }}

 

转载于:https://www.cnblogs.com/floodwater/p/10020347.html

你可能感兴趣的文章
[汇编语言学习笔记][第四章第一个程序的编写]
查看>>
android 打开各种文件(setDataAndType)转:
查看>>
补交:最最原始的第一次作业(当时没有选上课,所以不知道)
查看>>
Vue实例初始化的选项配置对象详解
查看>>
PLM产品技术的发展趋势 来源:e-works 作者:清软英泰 党伟升 罗先海 耿坤瑛
查看>>
vue part3.3 小案例ajax (axios) 及页面异步显示
查看>>
浅谈MVC3自定义分页
查看>>
.net中ashx文件有什么用?功能有那些,一般用在什么情况下?
查看>>
select、poll、epoll之间的区别总结[整理]【转】
查看>>
CSS基础知识(上)
查看>>
PHP中常见的面试题2(附答案)
查看>>
26.Azure备份服务器(下)
查看>>
mybatis学习
查看>>
LCD的接口类型详解
查看>>
Spring Boot Unregistering JMX-exposed beans on shutdown
查看>>
poi 导入导出的api说明(大全)
查看>>
Mono for Android 优势与劣势
查看>>
将图片转成base64字符串并在JSP页面显示的Java代码
查看>>
js 面试题
查看>>
sqoop数据迁移(基于Hadoop和关系数据库服务器之间传送数据)
查看>>