Common form of the form processing:
reg.html:
<! DOCTYPE HTML> <HTML lang = "EN"> <head> <Meta charset = "UTF-8"> <title> Registration Page </ title> </ head> <body> <form Action = "/ REG / "Method =" POST "> {%}% csrf_token <P> username: <INPUT type =" text "name =" username "> <span> error.user {{}} </ span> {# if there is an error ,} to obtain the error message # </ P> <P> password: <INPUT type = "password" name = "pwd"> <span> error.pwd {{}} </ span> {# if there is an error, it Get error} # </ P> <P> <INPUT type = "submit"> </p> </form> </body> </html>
views.py:
Import the render django.shortcuts from, the HttpResponse from app01 Import Models DEF REG (Request): error = { "User": "", "pwd": ""} # a dictionary stored with an error message if request.method == " the POST ": username = request.POST.get (" username ") password = request.POST.get (" pwd ") IF len (username)>. 5: error [" user "] =" user name can not be greater than 5 " IF len (password) <. 6: error [ "pwd"] = "password can not be less than 6" elif len (password)> 10: error [ "pwd"] = "password can not be greater than 10" return the render (Request, " reg.html ", {" error ": error})
Visit, http: //127.0.0.1: 8000 / reg /
Input is greater than 5-digit user name and password for more than 10 digits
Processing components form using form:
reg2.html:
<! DOCTYPE HTML> <HTML lang = "EN"> <head> <Meta charset = "UTF-8"> <title> Registration Page </ title> </ head> <body> <form Action = "/ reg2 / "Method =" POST "NOVALIDATE> {% csrf_token%} {} {} {# form_obj.as_p displayed in the tap form p} # {# {} {} {# form_obj.errors.username obtain separate error message #} username {# {{form_obj.errors.password}} { # acquired separately password error message} # <P> <INPUT type = "Submit"> </ P> </ form> </ body> </ HTML>
form_obj can get directly to the username, password error, the errors can also be obtained separately
views.py:
Import the render django.shortcuts from, the HttpResponse from app01 Import Models from Django Forms # Import component introduced form # define a form class class regform (forms.Form): username = forms.CharField ( min_length =. 5, label = "User Name", # set the tag name # error error_messages = { "min_length": "user name can not be greater than 5!" } ) password = forms.CharField ( min_length =. 6, label = "password", set the label # # error error_messages {= "min_length": "passwords can not be less than six!" } ) DEF REG2 (Request): form_obj = RegForm () # GET request, the object is instantiated form request.method == IF "POST": form_obj = regform (request.POST) # form to help us do check if form_obj.is_valid (): # determine whether there is value form_obj Pass return the render (Request, "reg2.html", { "form_obj": form_obj})
Visit, http: //127.0.0.1: 8000 / reg2 /