form the input tag inside the form, and set the properties of input
#The demand background generates the input tag inside the form and sets the input tag's properties, classRegisterform (Form): Email=Fields . Emailfield () Password=Fields . Charfield () Password2=Fields . Charfield () Code=Fields . Charfield () Avatar= fields. Filefield (widget=widgets. FileInput (attrs={'ID':'Inputavatar'})) defRegister (Request):ifRequest.method = ='GET': obj=Registerform ()returnRender (Request,'register.html', {'obj': obj}) <form method="POST"action="/register/"Enctype="Multipart/form-data"> {% Csrf_token%} {{Obj.avatar}} {{Obj.usernam} }</form>
View Code
To get the session value in the form, pass the request parameter
# form tag to get the value inside the request--rewrite the __init__ function def __init__ (Self, request, *args, * *Kwargs) : = Request Super (Registerform, self). __init__ (*args, **kwargs)
View Code
Form validates a field self.clean_ field name
#form tag validates a field defClean_code (self): Input_code= Self.cleaned_data.get ('Code') Session_code= Self.request.session.get ('Code')#please see the Check_code function ifInput_code! =Session_code:RaiseValidationError ('Verification Code Error') Else: returnInput_code#self.errors = {' Code ': [' captcha error '], ' xx ': [Error 1, error 2]}
View Code
Form validation multiple fields Self.clean
#Form label Federated data validation defClean (self):"""at this point, all input values have been obtained, and the two-pass input password is verified."""P1= Self.cleaned_data.get ('Password1') P2= Self.cleaned_data.get ('Password2') ifP1! =P2:RaiseValidationError ('two times the input password is inconsistent')#by default put in self.errors[' __all__ '] Else: returnSelf.cleaned_data#return None """self.errors = {' __all__ ': [' Two input password inconsistent '], ' xx ': [Error 1, error 2]} non_field_errors = ' __all__ ' foreground fetch needs to use this time to get the error at the front end; Obj.non_field_errors"""
View Code
Form validation multiple fields Self.clean key to indicate error message, convenient for front-end use
#Additional settings for the overall error defClean (self):ifP1! =P2:self.add_error ('Password2','two times the input password is inconsistent') #Do not throw an exception at this time because an exception is thrown #throwing Exceptions is also the execution of Self.add_error returnNoneElse: returnSelf.cleaned_data This error is displayed at the front: Obj.errors.password2
View Code
Error message for form Self.errors
#form label data validation error messageSelf.errors = {'username': [Error 1, error 2],'Password': [Error 1, error 2]}defClean_xx (self) If you encounter a mistake, put it in self.errors['xx'] InsidedefClean (self) If you encounter a mistake, put it in self.errors['__all__'] inside but if you want the front end to get self.errors['__all__'] Error, obj.errors.__all__ can't get it.but obj.non_field_errors, not self.errors.non_fields_errors.
View Code
Register form
#the complete forms.py #-*-coding:utf-8-*- fromDjango.formsImportForm, fields, widgets fromDjango.core.exceptionsImportValidationErrorclassRegisterform (Form): Username= fields. Charfield (widget=widgets. TextInput (Attrs={'class':"Form-control"})) password= fields. Charfield (widget=widgets. Passwordinput (Attrs={'class':"Form-control"})) Password2= fields. Charfield (widget=widgets. Passwordinput (Attrs={'class':"Form-control"})) Code= fields. Charfield (widget=widgets. TextInput (Attrs={'class':"Form-control"})) Avatar= fields. Filefield (widget=widgets. FileInput (attrs={'ID':'Inputavatar'})) def __init__(Self, request, *args, * *Kwargs): Self.request=Request Super (Registerform, self).__init__(*args, * *Kwargs)defClean_code (self): Input_code= Self.cleaned_data.get ('Code'). Upper () Session_code= Self.request.session.get ('Code'). Upper ()#please see the Check_code function ifInput_code! =Session_code:RaiseValidationError ('Verification Code Error') Else: returnInput_code#self.errors = {' Code ': [' captcha error '], ' xx ': [Error 1, error 2]} defClean (self):"""at this point, all input values have been obtained, and the two-pass input password is verified."""P1= Self.cleaned_data.get ('Password') P2= Self.cleaned_data.get ('Password2') ifP1! =P2:self.add_error ('Password2','two times the input password is inconsistent')#Do not throw an exception at this time because an exception is thrown #throwing Exceptions is also the execution of Self.add_error returnNone#raise ValidationError (' Two input passwords inconsistent ') #by default put in self.errors[' __all__ '] #execution is self.add_error (' __all__ ', ' two input password inconsistent ') Else: returnSelf.cleaned_data"""self.errors = {' __all__ ': [' two times input password inconsistent '], ' xx ': [Error 1, error 2]} non_field_errors = ' __all__ ' front desk access required"""
View Code
[Oldboy-django] [2 in-depth django]form form clean_xx, clean complete data validation + form error message