Python---The form component in Django (validation using custom methods before data is added, and source analysis)

Source: Internet
Author: User

Form Component code:

 fromapp02.models Import User fromdjango.core.exceptions Import ValidationErrorclassAjaxform (forms. Form): User=Fields . Charfield (Required=True, Min_length=3, Max_length=7,) email=Fields . Emailfield (Required=True,) #自定义方法 the Clean_ field name #必须返回值self. cleaned_data[ ' user '] #如果出错抛出raise validationerror ("Error ...")
#会在基础验证成功后, use a custom method to verify the def clean_user (self): v= self.cleaned_data[' user '] if User.objects.filter (username=v). Count (): #重复了 raise Valida Tionerror ("User name already exists") return v def clean_email (self): return self.cleaned_data[' email ']

If duplicate data is found in the database, an error is thrown.

Views Code:

def Ajax (req):ifReq.method = ="GET": obj=Ajaxform ()returnRender (req,"ajax.html",{"obj": obj}) Else: Ret={} obj=Ajaxform (req. POST)if obj.is_valid (): #在使用is_valid之后才会将数据进行验证ret['Status']="OK"            returnHttpResponse (Json.dumps (ret))Else: Print (obj.errors) ret['message']=obj.errorsreturnHttpResponse (Json.dumps (ret))

Start validating code after Is_valid and enter from here

Source view:

class baseform:       def is_valid (self):        "" "        Returns True If the form has no errors. Otherwise, False. If errors        is being ignored, returns FALSE.         "" returns True        if the form data is correct return self.errors #是属性方法 for field validation
 is  is not None #data传入表单数据不为空, so is_bound=true

Consider self.errors:

    @property    def errors (self):        "Returns a errordict forthedata provided for the form< /c5>"#返回错误信息为表单数据        if  is None:  #初始self. _errors is null                Self.full_clean () #进入该方法         return self._errors

Tracking Self.full_clean ():

def Full_clean (self):"""cleans all of self.data and populates self._errors and Self.cleaned_data. """Self._errors =errordict () #初始化错误字典ifNot Self.is_bound: # Stop further processing. returnSelf.cleaned_data={} #初始化正确数据 # If the form ispermitted to is empty, and none of the form data has # changed fromThe initial data, Shortcircuit any validation. ifself.empty_permitted and not self.has_changed (): #如果允许为空, and the data is changed from the initial state, it is returned directlyreturn#下面是开始验证的方法 Self._clean_fields () self._clean_form () Self._post_clean ( )

Start validation field: Self._clean_fields ()

def _clean_fields (self):
#循环字段, the field that is set in the form component, which is from the __new__ of Declarativefieldsmetaclass forName, fieldinchSelf.fields.items (): # value_from_datadict () gets the data fromThe data dictionaries. # Each widget type knows what to retrieve it own data, because some # widgets split data over several HTML Fiel Ds. ifField.disabled:value=Self.get_initial_for_field (field, name)Else: Value=field.widget.value_from_datadict (Self.data, Self.files, Self.add_prefix (name))Try: ifisinstance (field, Filefield): initial=Self.get_initial_for_field (field, name) value=Field.clean (value, initial)Else: Value=Field.clean (value) Self.cleaned_data[name]=value
         #上面尝试进行正则验证, after validation succeeds, the following logic begins
#会调用 clean_%s Method name is the field name, and this is our custom method, we can have the data after the regular validation has been satisfied
#上再次进行自定义函数的验证, such as verifying the uniqueness of database data processing ifHasattr (Self,'clean_%s'%name): Value= GetAttr (self,'clean_%s'%name) () Self.cleaned_data[name]=value #注意: The final value depends on the custom method: If the method already exists except validationerror ase: #在自定义方法上, if the validation is wrong, we need to throw the error to get the method to capture self.add_error (name, E)

Python---The form component in Django (validation using custom methods before data is added, and source analysis)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.