Django---ModelForm详解
示例:
from django.db import models
from django.forms import ModelForm
TITLE_CHOICES = (
('MR', 'Mr.'),
('MRS', 'Mrs.'),
('MS', 'Ms.'),
)
class Author(models.Model):
name = models.CharField(max_length=100)
title = models.CharField(max_length=3, choices=TITLE_CHOICES)
birth_date = models.DateField(blank=True, null=True)
def __str__(self): # __unicode__ on Python 2
return self.name
class Book(models.Model):
name = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
class AuthorForm(ModelForm):
class Meta:
model = Author #绑定数据库表
fields = ['name', 'title', 'birth_date'] #显示的字段(‘__all__’)
class BookForm(ModelForm):
class Meta:
model = Book
fields = ['name', 'authors']
选择用到的字段:
fields = [] 或 ‘__all__’
exclude = [ ]
save()方法:
每个ModelForm还具有一个save() 方法。这个方法根据表单绑定的数据创建并保存数据库对象。
模型表单的子类可以用关键字参数instance 接收一个已经存在的模型实例;如果提供,save() 将更新这个实例。
>>> from myapp.models import Article
>>> from myapp.forms import ArticleForm
# Create a form instance from POST data.
>>> f = ArticleForm(request.POST)
# 创建新对象
>>> new_article = f.save()
# Create a form to edit an existing Article, but use
# POST data to populate the form.
#更新该对象
>>> a = Article.objects.get(pk=1)
>>> f = ArticleForm(request.POST, instance=a)
>>> f.save()
重写(覆盖)默认的字段:
from django.forms import ModelForm, Textarea
from myapp.models import Author
class AuthorForm(ModelForm):
class Meta:
model = Author
fields = ('name', 'title', 'birth_date')
widgets = {
'name': Textarea(attrs={'cols': 80, 'rows': 20}),
}
覆盖字段:
from django.forms import ModelForm
from myapp.models import Article
from django.forms import fields
class ArticleForm(ModelForm):
slug = fields.ChoiceField()
class Meta:
model = Article
fields = ['pub_date', 'headline', 'content', 'reporter', 'slug']
提供初始值:
>>> article = Article.objects.get(pk=1)
>>> article.headline
'My headline'
>>> form = ArticleForm(initial={'headline': 'Initial headline'}, instance=article)
>>> form['headline'].value()
'Initial headline'
class XXXModelForm(ModelForm)
a.
class
Meta:
model,
# 对应Model的
fields
=
None
,
# 字段
exclude
=
None
,
# 排除字段
labels
=
None
,
# 提示信息
help_texts
=
None
,
# 帮助提示信息
widgets
=
None
,
# 自定义插件
error_messages
=
None
,
# 自定义错误信息(整体错误信息from django.core.exceptions import NON_FIELD_ERRORS)
field_classes
=
None
# 自定义字段类 (也可以自定义字段)
localized_fields
=
(
'birth_date'
,)
# 本地化,如:根据不同时区显示数据
如:
数据库中
2016
-
12
-
27
04
:
10
:
57
setting中的配置
TIME_ZONE
=
'Asia/Shanghai'
USE_TZ
=
True
则显示:
2016
-
12
-
27
12
:
10
:
57
b. 验证执行过程
is_valid
-
> full_clean
-
> 钩子
-
> 整体错误
c. 字典字段验证
def
clean_字段名(
self
):
# 可以抛出异常
# from django.core.exceptions import ValidationError
return
"新值"
d. 用于验证
model_form_obj
=
XXOOModelForm()
model_form_obj.is_valid()
model_form_obj.errors.as_json()
model_form_obj.clean()
model_form_obj.cleaned_data
e. 用于创建
model_form_obj
=
XXOOModelForm(request.POST)
#### 页面显示,并提交 #####
# 默认保存多对多
obj
=
form.save(commit
=
True
)
# 不做任何操作,内部定义 save_m2m(用于保存多对多)
obj
=
form.save(commit
=
False
)
obj.save()
# 保存单表信息
obj.save_m2m()
# 保存关联多对多信息
f. 用于更新和初始化
obj
=
model.tb.objects.get(
id
=
1
)
model_form_obj
=
XXOOModelForm(request.POST,instance
=
obj)
...
PS: 单纯初始化
model_form_obj
=
XXOOModelForm(initial
=
{...})