django之form表单验证

django中的Form一般有两种功能:

  • 输入html
  • 验证用户输入
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import re
from django import forms
from 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_choice = models.BookType.objects.values_list('id','caption')

    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'邮箱'}))
form表单验证属性常用写法大全

 

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))
View Code

 

 

#!/usr/bin/env python
# -*- coding:utf-8 -*-


from django import forms
from app_from import models

class Form1(forms.Form):
    user = forms.CharField(
        widget=forms.TextInput(attrs={'class': 'c1'}),
        error_messages={'required': '用户名不能为空'},)
    pwd = forms.CharField(max_length=4,min_length=2)
    email = forms.EmailField(error_messages={'required': '邮箱不能为空', 'invalid': '邮箱格式错误'})

    memo = forms.CharField(
        widget=forms.Textarea()
    )
    # user_type_choice = (
    #     (0, '普通用户'),
    #     (1, '高级用户'),
    # )
    user_type_choice = models.BookType.objects.values_list('id','caption')
    book_type = forms.CharField(
        widget=forms.widgets.Select(choices=user_type_choice,attrs={'class': "form-control"}))

    def __init__(self,*args, **kwargs):
        """
        这么写的目的是为了在更新数据库的时候每次都会执行这个方法
        :param args: 
        :param kwargs: 
        """
        super(Form1, self).__init__(*args, **kwargs)

        self.fields['book_type'] =  forms.CharField(
            widget=forms.widgets.Select(choices=models.BookType.objects.values_list('id','caption'),attrs={'class': "form-control"}))

 加了验证码的表单验证

 

下载这两个文件请点击--》【ooo】

 

 

from django.shortcuts import render,HttpResponse,HttpResponseRedirect

# Create your views here.

from app01.forms import Form1
import io
from check_code import check_code

def check_coder(request):
    mstream = io.BytesIO()
    img, code = check_code.create_validate_code()
    img.save(mstream,'GIF')
    request.session["CheckCode"] = code
    # print(mstream.getvalue())
    return HttpResponse(mstream.getvalue())
def login(request):
    if request.method == 'POST':
        print("aaa")
        f = Form1(request.POST)
        if f.is_valid():
            code_sess = request.session.get('CheckCode',None)
            """
            思路:首先获取session,然后获取验证码的内容,全部大写
            """
            code = f.cleaned_data['check_code']
            user = f.cleaned_data['user']
            print(code_sess,code)
            if code.upper() == code_sess.upper():
                print("验证码正确")
                print(code,user)
                return HttpResponseRedirect('/index/')

        else:
            print('bb')
            print(f.errors)
            return render(request,'login.html',{'error':f.errors,"ccc":"或者验证码错误",'form':f})
    else:
        f = Form1()
        return render(request,'login.html',{'form':f})
views

 

#!/usr/bin/env python
# -*- coding:utf-8 -*-

from django import forms
# from app_from import models

class Form1(forms.Form):
    user = forms.CharField(
        widget=forms.TextInput(attrs={'class': 'c1'}),
        # error_messages={'required': '用户名不能为空'},
    )
    check_code = forms.CharField(
        label='验证码',
        max_length=4,
        error_messages={'required': u'验证码不能为空', 'invalid': u'验证码不正确'},
    )
forms

 

{% extends "temp.html" %}
{% block login %}

    <form action="/login/" method="POST">
        <div class="input_group">

            {{form.user}}

            {% if error.user.0 %}
                <span>{{error.user.0}}</span>
            {% endif %}
            <div>
                {{form.check_code}}
                {% if error.check_code.0 %}
                    <span id="aaa">{{ ccc }}</span>
                {% endif %}
                <img src="/check_code/" onclick="ChangCode()" id="imgCode">
            </div>
        </div>
        <div>
            <input type="submit" value="提交">
        </div>
    </form>
    <script src="/static/js/jquery-1.12.4.js"></script>
    <script>
        console.log($("#aaa").val())
        function ChangCode() {
            var code = document.getElementById('imgCode')
            code.src += '?'
        }
    </script>
{% endblock %}
login.html

 

posted @ 2016-09-16 23:03  我当道士那儿些年  阅读(619)  评论(0编辑  收藏  举报