1. 定义ModelForm类
#froms.py
from django import forms
from app01.modles import User
class UserModelForm(forms.ModelForm):
class Meta:
model = User #关联的model类
fields = "__all__" #或('name','email','user_type') #验证哪些字段,"__all__"表示所有字段
exclude = None #排除的字段 ("id",)是元组
labels = None #提示信息
help_texts = None #帮助提示信息
widgets = None #自定义插件
#widgets = {
'username': TextInput(attrs={'class': 'form-control', 'style': '530px;', 'placeholder': u'必填项'}),}
error_messages = None #自定义错误信息(整体错误信息from django.core.exceptions import NON_FIELD_ERRORS)
field_classes = None #自定义字段类(也阔以自定义字段)
localized_fields = () #本地化,根据settings中TIME_ZONE设置的不同时区显示时间
2. ModelForm验证执行的过程
Form所有的钩子ModelForm都有。
is_valid() --> self.errors --> full_clean() --> self._clean_fields() --> clean_字段名(自定义方法)
self._clean_form() --> clean(self)
self._post_clean() (整体错误)
clean_字段名(自定义方法)
可以抛出异常
def clean_username(self):
value = self.cleaned_data['username']
if value == 'root':
return value
else:
raise ValidationError("你不是管理员!")
3.views.py 视图处理处理
def ueser_get(request):
if request.method == "POST":
u_form = UserModelForm(request.POST)
if u_form.is_valid():
u_form.save()
tips = u"增加成功!"
display_control = ""
else:
tips = u"增加失败!"
display_control = ""
return render(request, "user_add.html", locals())
else:
display_control = "none"
u_form = UserModelForm()
return render(request, "user_add.html", locals())
4.user_add.html
u_form.as_p # 生成列表