1、form组件(******)
局部钩子
全局钩子
'''
实例化时:
self.fields={
"username":"字段规则对象",
"password":"字段规则对象",
}
is_valid时:
self._errors = {}
self.cleaned_data = {}
#局部钩子:
for name, field in self.fields.items():
try:
value = field.clean(value)
self.cleaned_data[name] = value
if hasattr(self, 'clean_%s' % name):
value = getattr(self, 'clean_%s' % name)()
self.cleaned_data[name] = value
except ValidationError as e:
self.add_error(name, e)
# 全局钩子:
self.clean() # def self.clean():return self.cleaned_data
return not self.errors # True或者False
'''
使用组件:
form.py
class LoginForm(forms.Form):
username=forms.CharField()
views.py:
def login(request):
if request.is_ajax():
loginform=LoginForm(request.POST)
loginResponse={"user":None,"error_msg":None}
if loginform.is_valid():
loginResponse["user"]=username
# session操作
else:
loginResponse["error_msg"]loginform.errors
return Httpresponse(json.dumps(loginResponse))
loginform=LoginForm()
return(request,"login.html",{"loginform":loginform})
login.html:
<form>
{{loginform.username}}
<input type="button" value="submit" id="subBtn">
</form>
<script>
$("#subBtn").click(function(){
$.ajax({
url:"/login/",
type:"POST",
data:{},
success:function(data){
// data loginResponse
}
})
})
</script>