-
form
from django import forms from django.core.exceptions import ValidationError class RegForm(forms.Form): name = forms.CharField( required = True, min_length =6, label = '姓名', error_messages = { 'required':'不能为空', 'invalid':'格式不正确' } ) password = forms.CharField(widget=forms.PassworInput()) gender = forms.ChoicesField(choices=((1,'男'),(2,'女'))) #局部钩子 def clean_name(self): # 通过校验 返回正确的值 # 不通过校验 抛出异常 raise ValidationError('错误信息') # 全局钩子 def clean(self): # 通过校验 返回self.cleaned_data # 不通过校验 # 自己将错误信息添加到指定字段 self.add_error(’‘,'错误信息' ) # 抛出异常 raise ValidationError('错误信息') # 视图中使用: form_obj = RegForm() form_obj = RegForm(request.POST) form_obj.is_valid() form_obj.fields # 有序字典 name:字段的对象 # 模板中使用: {{ form_obj.as_p }} {{ form_obj.errors }} {{ form_obj.name }} {{ form_obj.name.label }} {{ form_obj.name.id_for_label }} {{ form_obj.name.errors }} {{ form_obj.name.errors.0 }}
-
modelform
from django import forms
from app01 import models
class RegForm(forms.ModelForm):
re_password = forms.CharField(widget=forms.PassworInput())
class Meta:
model = models.User
fields = '__all__' # ['name','password']
exclude = ['name']
labels = {
'name':'姓名' # 直接给model中的字段加verbose_name
}
error_messages={
'name' = {
}
}
widgets = {
'password':widget=forms.PassworInput(attrs={'class':'form-control'})
}
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
for field in self.fields.values():
field.widget.attrs.update({'class':'form-control'})
# 视图中使用:
form_obj = RegForm(request.POST)
form_obj.is_valid():
form_obj.save()