Python 21st Day

Source: Internet
Author: User

Form form

Sample program:

1. Create a Form Class

#!/usr/bin/env python#-*-coding:utf-8-*-ImportRe fromDjangoImportForms fromDjango.core.exceptionsImportvalidationerror# Custom Phone number verification functiondefmobile_validate (value): Mobile_re= Re.compile (r'^ (13[0-9]|15[012356789]|17[678]|18[0-9]|14[57]) [0-9]{8}$')    if  notMobile_re.match (value):RaiseValidationError ('cell phone number format error')classPublishForm (forms. Form): User_type_choice=((0, U'Normal User'),        (1, U'Advanced users'),) User_type= Forms. Integerfield (Widget=forms.widgets.select (choices=User_type_choice, Attrs={'class':"Form-control"})) title= Forms. Charfield (max_length=20, Min_length=5, Error_messages={'Required': U'title cannot be empty',                                            'Min_length': U'The title is a minimum of 5 characters',                                            'Max_length': U'title up to 20 characters'}, Widget=forms. TextInput (attrs={'class':"Form-control",                                                          'placeholder': U'title 5-20 characters'}) Memo= Forms. Charfield (required=False, Max_length=256, Widgets=forms.widgets.textarea (attrs={'class':"Form-control No-radius",'placeholder': U'Detailed Description','rows': 3})) Phone= Forms. Charfield (validators=[Mobile_validate,], error_messages={'Required': U'The phone cannot be empty'}, Widget=forms. TextInput (attrs={'class':"Form-control",                                                          'placeholder': U'Mobile phone number'})) Email= Forms. Emailfield (required=False, Error_messages={'Required': U'The mailbox cannot be empty','Invalid': U'Bad mailbox Format'}, Widget=forms. TextInput (attrs={'class':"Form-control",'placeholder': U'Email'}))

2. View

defPublish (Request): RET= {'Status': False,'Data':"','Error':"','Summary':"'}    ifRequest.method = ='POST': Request_form=PublishForm (Request. POST)ifrequest_form.is_valid (): Request_dict=Request_form.clean ()Printrequest_dict ret['Status'] =TrueElse: Error_msg=Request_form.errors.as_json () ret['Error'] =json.loads (error_msg)returnHttpResponse (Json.dumps (ret))
Csrf

1. Normal form, send token again to the server via form

set the return value in Veiw: return render_to_response ('account/login.html', data,context_instance=  RequestContext (Request))     or    return'xxx.html', Data),  set token in HTML: {% csrf_token%}

2. Ajax

view.py

 fromDjango.template.contextImportRequestContext#Create your views here.    defTest (Request):ifRequest.method = ='POST':        Printrequest. POSTreturnHttpResponse ('OK')    returnRender_to_response ('app01/test.html', Context_instance=requestcontext (Request))

Text.html

<! DOCTYPE Html>"en"> <meta charset="UTF-8"> <title></title>    {% Csrf_token%}      <input type="Button"onclick="Do ();"Value="Do it"/> <script src="/static/plugin/jquery/jquery-1.8.0.js"></script> <script src="/static/plugin/jquery/jquery.cookie.js"></script> <script type="Text/javascript">var csrftoken= $.cookie ('Csrftoken'); function Csrfsafemethod (method) {These HTTP methods do notRequire CSRF protectionreturn(/^ (get| head| options| TRACE) $/. Test (method)); } $.ajaxsetup ({beforesend:function (XHR, settings) {if(!csrfsafemethod (Settings.type) &&!this.crossdomain) {Xhr.setrequestheader ("X-csrftoken", Csrftoken);        }            }        }); function do () {$.ajax ({URL:"/app01/test/", Data:{id:1}, type:'POST', Success:function (data) {Console.log (data);          }            }); }    </script></body>

Python 21st Day

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.