Convert form in Django

Source: Internet
Author: User

Https://www.cnblogs.com/chenchao1990/p/5284237.html

 

Form

 

1. Use Form

In Django, form generally has two functions:

1. Generate HTML tags

2. Verify the input content

To use the form provided by Django, you must import the form module in views.

From Django import forms

Then define a class that generates the input tag in the Form on the front-end HTML page.

1 class UserInfo(forms.Form):2     email = forms.EmailField()3     host = forms.CharField()4     port = forms.CharField()5     mobile = forms.CharField()

 

 

Custom from process:

 

2. Let's talk about the Code directly:
1 # Coding: UTF-8 2 3 4 from Django import Forms 5 6 class userinfo (forms. form): # defines the Django Form 7 email = forms. emailfield () 8 host = forms. charfield () 9 port = forms. charfield () 10 mobile = forms. charfield () 11 12 def user_list (request): 13 14 OBJ = userinfo () # create a form object 15 if request. method = "Post": 16 user_input_obj = userinfo (request. post) # request. post is all submitted data 17 18 if user_input_obj.is_valid (): # is_valid judge whether the input content is valid ture or false19 DATA = user_input_obj.clean ()#. clen () Get submitted data 20 21 host_name = data ['host'] 22 print data23 print host_name24 else: # If the input is invalid, return Error 25 error_msg = user_input_obj.errors # errors is error 26 return render(request,'user_list.html ', {'obj': user_input_obj, 'error': error_msg }) 27 # Return the error message to the front-end page to display 28 return render(request,'user_list.html ', {'obj': OBJ })

 

Front-end HTML page:

1 <! Doctype HTML> 2 <HTML lang = "en"> 3 

 

 

3. custom form

1. custom error message

  • Error_messages = {'required': U' mobile phone cannot be blank '},

 

1 class userinfo (forms. form): 2 email = forms. emailfield (error_messages = {'required': U' mailbox cannot be blank '},) 3 host = forms. charfield (error_messages = {'required': U' host cannot be empty '},) 4 Port = forms. charfield (error_messages = {'requestred': U' port cannot be blank '},) 5 mobile = forms. charfield (error_messages = {'requestred': U' mobile phone cannot be blank '},)

 

 

2. custom form style attributes

  • Widget = forms. textinput (attrs = {'class': "form-control ",
    'Placeholder': u'mobile phone number '}),
1Class userinfo (forms. Form ):2 email = forms. emailfield (error_messages = {'required': U' mailbox cannot be blank '},) 3 host = forms. charfield (error_messages = {'required': U' host cannot be empty '},) 4 Port = forms. charfield (error_messages = {'requestred': U' port cannot be blank '},) 5 mobile = forms. charfield (error_messages = {'requestred': U' mobile phone cannot be blank '}, 6Widget = forms. textinput(Attrs = {'class': "form-control", 7 'placeholder': u'mobile phone number'}),) 8 9 memo = forms. charfield (required = false, # The default input can be blank. 10Widget = forms. textarea(Attrs = {'class': "form-control", 11 'holder': U "Remarks "}))

 

 

3. Custom verification form content is valid:

  • validators=[mobile_validate, ],
1 From Django. Core. Exceptions import validationerror 2 Import RE 3 4 5 defMobile_validate(Value): 6 mobile_re = Re. compile (R' ^ (13 [0-9] | 15 [012356789] | 17 [678] | 18 [0-9] | 14 [57]) [0-9] {8} $ ') 7 if not mobile_re.match (value): 8 raise validationerror ('mobile Phone Number Format error') 9 10 11 class userinfo (forms. form): 12 email = forms. emailfield (error_messages = {'required': U' mailbox cannot be blank '},) 13 host = forms. charfield (error_messages = {'required': U' host cannot be empty '},) 14 Port = forms. charfield (error_messages = {'requestred': U' port cannot be blank '},) 15 mobile = forms. charfield (Validators = [mobile_validate,],16 error_messages = {'required': U' mobile phone cannot be blank '}, 17 widget = forms. textinput (attrs = {'class': "form-control", 18 'holder': u'mobile phone number'}),) 19 20 memo = forms. charfield (required = false, # The default input can be null. 21 widgets = forms. textarea (attrs = {'class': "form-control", 22 'placeholder': U "Remarks "}))

 

 

4. Select in custom form

1 class userinfo (forms. Form): 2 3 4User_type_choice= (5 (0, U'common user'), 6 (1, U 'advanced user'), 7) 8 user_type = forms. integerfield (widget = forms. widgets.Select(Choices =User_type_choice, 9 attrs = {'class': "form-control"}) 10 11 email = forms. emailfield (error_messages = {'required': U' mailbox cannot be blank '},) 12 host = forms. charfield (error_messages = {'required': U' host cannot be empty '},) 13 Port = forms. charfield (error_messages = {'requestred': U' port cannot be blank '},) 14 Mobile = forms. charfield (validators = [mobile_validate,], 15 error_messages = {'requestred': U' mobile phone cannot be blank '}, 16 widget = forms. textinput (attrs = {'class': "form-control", 17' placeholder ': U' mobile phone number'}),) 18 19 memo = forms. charfield (required = false, # The default input can be empty. 20 widgets = forms. textarea (attrs = {'class': "form-control", 21 'placeholder': U "Remarks "}))

 

 

5. Customize the error message Style

1. form error message:

If no processing is performed, the error message will display a default <ul> style. We can remove it and add it after the error message.As_data (): displays the original data.

  • User_input_obj.errors.as_data ()

This is not enough. You also need to retrieve the error information in the front-end page tag. However, the template language does not support the index value method. Therefore, you need to combine it with python.

Create a templatetags directory under the app directory, and then create a py file named form_tag.py.

 1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3  4 from django import template 5  6 register = template.Library() 7  8 @register.simple_tag 9 def error_message(arg):10     if arg:11         return arg[0][0]12     else:13         return ‘‘

 

Then, import the form_tag on the front-end page and use

1 {% load form_tag %}Import a py file2 <! Doctype HTML> 3 <HTML lang = "en"> 4 The writing method has changed.13 <p> port: {obj. port }}< span >{{ errors. port }}</span> </P> 14 <p> Email: {obj. email }}< span >{{ errors. email }}</span> </P> 15 <p> mobile phone: {obj. mobile }}< span >{{ errors. mobile }}</span> </P> 16 <p> Note: {obj. memo }}< span >{{ errors. memo }}</span> </P> 17 <input type = "Submit" value = "Submit"> 18 19 </form> 20 21 </body> 22 </ HTML>

 

 

2. Ajax error message:

  • User_input_obj.errors.as_json ()

HTML file: defines Ajax

 

 1 {% load staticfiles %} 2 <!DOCTYPE html> 3 

 

Background processing:

UseHttpresponse

1 def login (request): 2 3 OBJ = account_forms.userinfo (request. post) 4 If request. method = 'post': 5 If obj. is_valid (): 6 data = obj. clean () 7 print data 8 9 else: 10 error_msg = obj. errors. as_json () 11 return httpresponse (error_msg) # return data in httpresponse mode 12 Return render (request, 'account/login.html ', {'obj': OBJ }) 13 return render (request, 'account/login.html ', {'obj': OBJ })

 

 

Convert 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.