Django中创建基于数据模型的formset

和模型表单对象一样,我们也可以通过数据模型来生成formset对象。比如:

>>>  from django. forms. models  import modelformset_factory
>>> AuthorFormSet  = modelformset_factory (Author )

通过模型对象生成的formset和普通的formset一样:

>>> formset  = AuthorFormSet ( )
>>>  print formset
< input  type = "hidden" name = "form-TOTAL_FORMS" value = "1"  id = "id_form-TOTAL_FORMS" / >< input  type = "hidden" name = "form-INITIAL_FORMS" value = "0"  id = "id_form-INITIAL_FORMS" / >< input  type = "hidden" name = "form-MAX_NUM_FORMS"  id = "id_form-MAX_NUM_FORMS" / >
<tr ><th ><label  for = "id_form-0-name" >Name: </label ></th ><td >< input  id = "id_form-0-name"  type = "text" name = "form-0-name" maxlength = "100" / ></td ></tr >
<tr ><th ><label  for = "id_form-0-title" >Title: </label ></th ><td >< select name = "form-0-title"  id = "id_form-0-title" >
<option value = "" selected = "selected" >--------- </option >
<option value = "MR" >Mr. </option >
<option value = "MRS" >Mrs. </option >
<option value = "MS" >Ms. </option >
</select ></td ></tr >
<tr ><th ><label  for = "id_form-0-birth_date" >Birth date: </label ></th ><td >< input  type = "text" name = "form-0-birth_date"  id = "id_form-0-birth_date" / >< input  type = "hidden" name = "form-0-id"  id = "id_form-0-id" / ></td ></tr >

如果我们是基于模型对象创建的formset,那么我们可以利用模型对象的查询方法来定制formset包含的结果集。比如下面这样:

>>> formset  = AuthorFormSet (queryset =Author. objects. filter (name__startswith =’O’ ) )

或者,我们也可以自定义一个formset的子类,来重载其中的查询方法:

from django. forms. models  import BaseModelFormSet
class BaseAuthorFormSet (BaseModelFormSet ):
     def  __init__ ( self , *args , **kwargs ):
         super (BaseAuthorFormSet ,  self ). __init__ (*args , **kwargs )
         self. queryset  = Author. objects. filter (name__startswith =’O’ )

然后将这个自定义类作为创建formset的一个参数:

>>> AuthorFormSet  = modelformset_factory (Author , formset =BaseAuthorFormSet )

如果我们想创建一个不包含任何数据的空的formset,可以用下面的方法。

>>> AuthorFormSet (queryset =Author. objects. none ( ) )

和模型表单对象类似,我们可以通过fields和exclude方法来定义一个Formset中,包含哪些字段或者不包含哪些字段:

>>> AuthorFormSet  = modelformset_factory (Author , fields = (’name’ , ’title’ ) )
>>> AuthorFormSet  = modelformset_factory (Author , exclude = (’birth_date’ , ) )

模型表单对象中的save()方法可以将表单对象中的数据保存到数据库,同样的,formset对象也提供了一个save()方法,实现同样的功能:

# Create a formset instance with POST data.
>>> formset  = AuthorFormSet (request. POST )
# Assuming all is valid, save the data.
>>> instances  = formset. save ( )

其他有关基于数据模型的formset的应用,比如在视图和模板对象中的使用等,与标准的formset相同,具体请参考:

 
 

你可能感兴趣的:(django)