Form in Django

Source: Internet
Author: User

1. hand-writing a form to submit data

  • Input tags are available for users to fill in data
  • Validate form data extraction
  • Error Message

HTML page code:

<! Doctype HTML> <HTML lang = "ZH-CN"> 

View business logic code:

From Django. shortcuts import render, httpresponsefrom Django import forms # create your views here. class regform (forms. form): User = forms. charfield (max_length = 32) Pwd = forms. charfield (max_length = 32) def login (request): # globally defines the value of the variable, the value error_name = "" error_pwd = "" # "error_pwd =" "is required for the first GET request. The second incoming request is for the POST request to submit data if request. method = "Post": Print (123) # obtain the user input value user = request. post. get ("user") Pwd = request. post. Get ("PWD") print (User) print (PWD) # determine the data after obtaining the data if Len (User)> 6 and Len (PWD)> 6: # If the data meets the requirements, the registration is successful. Here, an httpresponse object return httpresponse ("registered successfully") Elif Len (User)> 6 and Len (PWD) is returned) <6: # the user name must be greater than 6 characters, but the password must be less than 6 Characters error_pwd = "this is a little short ~~~ "Elif Len (User) <6 and Len (PWD)> 6: # the username length is greater than 6, and the password is less than 6 error_name =" this is a little short !!! "Else: error_name =" this is a little short !!! "Error_pwd =" this is a little short ~~~ "# Return an HTML login page return render (request," register.html ", {" error_name ": error_name," error_pwd ": error_pwd })

2. In Django, form submits data:

Forms code:

 

From Django import formsfrom app_form.models import userfrom Django. core. exceptions import validationerrorfrom Django. forms import widgetsfrom Django. core. validators import regexvalidatorfrom app_form. models import user, hobbyimport re # verify the information in the validation input box (custom validation) def check_name (value): If "snow" in value: raise validationerror ("You are not from this day") # define form class to inherit forms. form (must inherit) Class regform (forms. form): # The type string of the attribute in the specified class cannot exceed 32 characters. User = forms. charfield (Label = "username", # the words "max_length = 12" are displayed when the input tag is generated, # The maximum length of the user name input box cannot exceed 32 characters min_length = 6, # the user name input box cannot be less than 6 characters required = true, # indicates that the result required for this input box is false, that is, initial = "snow" can be empty. # initial translation is the first and initial one, that is to say, the first access to the input box is the specified value "snow" Disabled = false, # disable translation is disabled, indicating that the disabled nature of the input box is false, it indicates that the value validators = [check_name] can be entered. # The translation means verification, that is, passing the value entered by the user to the check_name function to verify error_messages = {"min_length ": "You are too short ..., less than 6 "," required ":" cannot be blank "}) # The character string of the Password attribute in the specified class must be no less than 32 characters Pwd = forms. charfield (max_length = 12, # the maximum length of the password cannot exceed 12 characters min_length = 6, # the minimum length of the password is not less than 6 Characters label = "password ", # When the input box is generated, it indicates the role of this input box. error_messages = {"min_length": "You are too short.", "max_length ": "You are too long to stand it... "," required ":" cannot be blank "}) Gender = forms. choicefield (choices = (1, "male"), (2, "female"), (3, "unknown ")), # Only One widget = widgets can be selected for a single response. radioselect (), label = "gender") Hoby = forms. choicefield (choices = (1, "soccer"), (2, "basketball"), (3, "two-color ball"), widget = widgets. checkboxselectmultiple, label = "hobby") Phone = forms. charfield (Label = "mobile phone number", validators = [regexvalidator (R "^ 1 [3-9] \ D {9} $", "mobile phone number is not serious") # mode: regexvalidator (Regular Expression, error message)]) # Pwd = forms. charfield (# label = "password", # min_length = 6, # max_length = 12, # widget = widgets. passwordinput () #) re_ped = forms. charfield (Label = "Confirm Password", min_length = 6, max_length = 12, widget = widgets. passwordinput ())

 

HTML code:

<! Doctype HTML> <HTML lang = "ZH-CN"> 

Business Logic code:

Def register (request): form_obj = regform () # instantiate the regform object in a form to get the attributes and methods of regform print ("first instantiated object:", form_obj, type (form_obj) If request. method = "Post": # re-instantiate a regform object, you can get all the attributes and methods of regform form_obj = regform (request. post) print ("second instantiated object:", form_obj, type (form_obj) print ("error message:", form_obj.errors, type (form_obj.errors) for K, V in form_obj.errors.items (): Print (K, v) If form_obj.is_valid (): # cleaned_data is the verified data print (form_obj.cleaned_data) # Get A {'user ': 'tianwang Gaidi tiger, Xiaomi one-meter-five ', 'pwd': '000000'} dictionary print (form_obj.cleaned_data ["user"]) print (form_obj.cleaned_data ["PWD"]) # indicates that the registration is successful and you can enjoy the "service" provided. # return to a successful registration page, indicating that the registration is successful. Return httpresponse ("registered successfully ") # One access request is a GET request, returning an HTML page return render (request, "register2.html", {"form_obj": form_obj })

 

3 Hook Functions

3.1> Local hook function code:

# The local hook function only verifies the validation of a field def clean_phone (Self): # self indicates who is the validation, clean_data is the dictionary value = self obtained after being verified by the browser. cleaned_data.get ("phone") # obtain the data entered by the user and perform regular expression matching if Re. match (r '1 [3-9] \ D {9} ', value): # match (Regular Expression, string to be matched) return value # When the mobile phone number matches successfully, returns a valid mobile phone number. # If the matching fails, an exception is thrown. Raise validationerror ("Incorrect mobile phone number") def clean_re_ped (Self ): # obtain user-entered passwords Pwd = self. cleaned_data.get ("PWD") re_pwd = self. cleaned_data.get ("re_pwd") # judge whether the two passwords are consistent if Pwd = re_pwd: # When the two results are consistent, return the dictionary of the data return self. cleaned_data # When PWD is not equal to re_pwd, an exception is thrown and returned to the browser raise validationerror ("two different passwords ")

3.2> code of the global hook function:

# Global hook function def clean (Self): # The Global hook is that all fields in forms can be checked. # obtain the two passwords to verify Pwd = self. cleaned_data.get ("PWD") re_pwd = self. cleaned_data.get ("re_pwd") # determine whether the two results are correct if Pwd = re_pwd: return self. cleaned_data # add error message self. add_error ("re_pwd", "two check results inconsistent") Raise validationerror ("two check results inconsistent ")

Summary: main functions of the form component:

  • Generate available tags on the page
  • Verify the data submitted by the user
  • Retain the last entered content

 

Form in Django

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.