Django form Process 1, create class, inherit form. Form2, pages automatically create HTML tags based on the object of the Class 3, submit, request. POSTencapsulated in the object of the class, Obj=userinfo (Request. POST)4, the user input is legalobj.is_valid ()
5, all legal, access to all contentObj.clean ()
6. There is no legalobj.errors
First close the cross-site request # ' Django.middleware.csrf.CsrfViewMiddleware ', there is an error that prevents the submission and prompts for a successful submission of the error message, which can be obtained to the committed value
Form CustomizationCustom error message Mail = forms. Emailfield (error_messages={' Required ': U ' mailbox cannot be empty ') custom error rule mobile = forms. Charfield (Validators=[mobile_validate,], error_messages={' Required ': U ' phone cannot be empty '})
From django.shortcuts import renderfrom Django import formsimport refrom django.core.exceptions Import Validationerrordef mobile_validate (value): Mobile_re = Re.compile (R ' ^ (13[0-9]|15[012356789]|17[678]|18[0-9]|14[57] ) [0-9]{8}$ ') if not Mobile_re.match (value): Raise ValidationError (' cell phone number format error ') Class UserInfo (forms. Form): email = forms. Emailfield (error_messages={' Required ': U ' mailbox cannot be empty '}) host = forms. Charfield (error_messages={' Required ': U ' host cannot be empty '}) port = forms. Charfield (error_messages={' Required ': U ' port cannot be empty '}) Mobile = forms. Charfield (Validators=[mobile_validate,], #定义错误规则函数 error_messages={' required ': U ' phone cannot be empty '}, WI Dget=forms. TextInput (attrs={' class ': ' Form-control ', #定义class ' placeholder ': U ' enter phone number '})) Beizhu = forms. Charfield (Required=false, #备注允许为空 widget=forms. Textarea (attrs={' class ': ' Form-control ', #定义为多行输入框 ' placeholder ': U ' enter remarks '})) User_type_choice = ((0, U ' normal user '), (1,u ' Advanced user '),) User_type = forms. Integerfield (Widget=forms.widgets.select (choices=user_type_choice,attrs={' class ': ' Form-control '))
Save user input
obj = accountform.loginform (Request. POST)
Form Form validation and error messageserror message Format:Normal Format:
From django.shortcuts import render,httpresponsefrom web.forms import account as Accountformdef login (Request): obj = Accountform.loginform (Request. Post) if Request.method = = ' Post ': if Obj.is_valid (): all_data = Obj.clean () else: #用于Form表单提交 E Rror = obj.errors #print error[' username '][0] #print error[' password '][0] return render (Request, ' Account/lo Gin.html ', {' obj ': obj, ' ERROR ': Error}) return render (Request, ' account/login.html ', {' obj ': obj})
Create a simple_tag to make it error[' username '][0]
{% load xx%}<! DOCTYPE html>def Login (Request): obj = accountform.loginform (Request. Post) If Request.method = = ' Post ': If Obj.is_valid (): All_data = Obj.clean () Else: #用于Ajaxerror = Obj.errors.as_json () #print Errorreturn HttpResponse (Error) return render (Request, ' Accou Nt/login.html ', {' obj ': obj, ' ERROR ': Error}) return render (Request, ' account/login.html ', {' obj ': obj}) <body> <form action= "/login/" method= "POST" > <p>{{obj.username}} {% error_msg Error.username%} </p> <p>{{Obj.password}} {% error_msg error.password%} </p> <input type= "Submit" value= "Ajax Commit" onclick= "Submitajax ()" > </form> <script src= "{{ Static_url}}js/jquery-2.1.4.min.js "></script> <script>function Submitajax () { $.ajax ({ URL: '/login/', type: ' POST ', data:{' username ': ', ' Password ': '},success:function (ARG) { Console.log (arg )}} </script></body>
form Generation Select label
Static Select Dynamic Select
When you increase database datawill not be updated unless the program is closed and re-loaded will not be updated
WORKAROUND: Take advantage of the static field of the object-oriented class From Django Import Formsimport jsonclass importform (forms. Form): #静态selectHOST_TYPE_LIST = ( (0, ' physical Machine '), (1, ' virtual machine '),) Host_type = forms. Integerfield ( widget=forms. Select (choices=host_type_list) ) hostname = forms. Charfield () #动态select # admin_dic = ((1, ' YANGMV '), (1, "Bob"),) # w_obj = open (' Db_admin ', ' W ') # W_ Obj.write (Json.dumps (Admin_dic)) # w_obj.close () f_obj = open (' Db_admin ', ' r ') data = F_obj.read () Data_tuple = json.loads (data) admin = forms. Integerfield ( widget=forms. Select (choices=data_tuple) ) def __init__ (Self,*args,**kwargs): super (Importform,self). __init__ ( *args,**kwargs) tmp = open (' db_admin ') data = Tmp.read () data_tuple = json.loads (data) self.fields[' admin '].widget.choices = data_tuple
Add database data again, refresh the page directly to read the new data optimized codeFrom Django Import Formsimport jsonclass importform (forms. Form): admin = forms. Integerfield (widget=forms. Select ()) def __init__ (Self,*args,**kwargs): super (Importform,self). __init__ (*args,**kwargs) tmp = Open (' db_admin ') data = Tmp.read () data_tuple = json.loads (data) self.fields[' admin '].widget.choices = Data_tuple
get Select data using models(Models operation, later in the article will be described in detail) Class Select (models. Model): username = models. Charfield (max_length=16) password = models. Charfield (MAX_LENGTH=32)
<body> <form action= "/home/" > <p>{{obj.admin}}</p> </form></body >
DEF home (Request): obj = homeform.importform () return render (Request, ' home/home.html ', {' obj ': obj})
models. Select.objects.all (). Values_list (' id ', ' username ')
Django-form forms (Validation, customization, error messages, Select)