首页 > 代码库 > Python 21st Day

Python 21st Day

Form 表单

示例程序:

1. 创建表单类

#!/usr/bin/env python# -*- coding:utf-8 -*-import refrom django import formsfrom django.core.exceptions import ValidationError# 自定义手机号验证函数def 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(手机号码格式错误)class PublishForm(forms.Form):    user_type_choice = (        (0, u普通用户),        (1, u高级用户),    )    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标题不能为空,                                            min_length: u标题最少为5个字符,                                            max_length: u标题最多为20个字符},                            widget=forms.TextInput(attrs={class: "form-control",                                                          placeholder: u标题5-20个字符}))    memo = forms.CharField(required=False,                           max_length=256,                           widget=forms.widgets.Textarea(attrs={class: "form-control no-radius", placeholder: u详细描述, rows: 3}))    phone = forms.CharField(validators=[mobile_validate, ],                            error_messages={required: u手机不能为空},                            widget=forms.TextInput(attrs={class: "form-control",                                                          placeholder: u手机号码}))    email = forms.EmailField(required=False,                            error_messages={required: u邮箱不能为空,invalid: u邮箱格式错误},                            widget=forms.TextInput(attrs={class: "form-control", placeholder: u邮箱}))

2. view 

def publish(request):    ret = {status: False, data: ‘‘, error: ‘‘, summary: ‘‘}    if request.method == POST:        request_form = PublishForm(request.POST)        if request_form.is_valid():            request_dict = request_form.clean()            print request_dict            ret[status] = True        else:            error_msg = request_form.errors.as_json()            ret[error] = json.loads(error_msg)    return HttpResponse(json.dumps(ret))

CSRF

1. 普通表单,通过表单的方式将token再次发送到服务端

veiw中设置返回值:  return render_to_response(Account/Login.html,data,context_instance=RequestContext(request))       或者   return render(request, xxx.html, data)  html中设置Token:  {% csrf_token %}

2. Ajax

view.py

from django.template.context import RequestContext# Create your views here.    def test(request):      if request.method == POST:        print request.POST        return HttpResponse(ok)    return  render_to_response(app01/test.html,context_instance=RequestContext(request))

text.html

<!DOCTYPE html><html><head lang="en">    <meta charset="UTF-8">    <title></title></head><body>    {% csrf_token %}      <input type="button" onclick="Do();"  value=http://www.mamicode.com/"Do it"/>      <script src=http://www.mamicode.com/"/static/plugin/jquery/jquery-1.8.0.js"></script>    <script src=http://www.mamicode.com/"/static/plugin/jquery/jquery.cookie.js"></script>    <script type="text/javascript">        var csrftoken = $.cookie(csrftoken);          function csrfSafeMethod(method) {            // these HTTP methods do not require CSRF protection            return (/^(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></html>

 

Python 21st Day