首页 > 代码库 > 1217

1217

1.django实现form表单验证

使用django内置功能实现用户输入信息的验证

新建一个project,比如叫django1217;

新建一个app,python manage.py startapp app01

settings,py,

INSTALLED_APPS = [
    django.contrib.admin,
    django.contrib.auth,
    django.contrib.contenttypes,
    django.contrib.sessions,
    django.contrib.messages,
    django.contrib.staticfiles,
    app01,#注册了ap01
]

MIDDLEWARE = [
    django.middleware.security.SecurityMiddleware,
    django.contrib.sessions.middleware.SessionMiddleware,
    django.middleware.common.CommonMiddleware,
    # ‘django.middleware.csrf.CsrfViewMiddleware‘,  #注释这行
    django.contrib.auth.middleware.AuthenticationMiddleware,
    django.contrib.messages.middleware.MessageMiddleware,
    django.middleware.clickjacking.XFrameOptionsMiddleware,
]

#设置静态资源路径
STATIC_URL = /static/
STATICFILES_DIRS = (
    os.path.join(BASE_DIR,static),
)

urls.py,

from app01 import views

urlpatterns = [
    url(r^admin/, admin.site.urls),
    url(r^login/, views.login),
]

app01→views.py,

from django.shortcuts import render

# Create your views here.

from django import forms

#定义各个输入框的规则,比如下面的不允许user和pwd为空
class LoginForm(forms.Form):

#字段的值比如跟html中该标签的name值一样
#比如这里的user对应html里<input type="text" name="user" />中的name值。
    user = forms.CharField(required=True)
    pwd = forms.CharField(required=True)

def login(request):
    if request.method == POST:
        # u = request.POST.get(‘user‘)
        # p = request.POST.get(‘pwd‘)
        # print(u,p)
        obj = LoginForm(request.POST)

#如果所有规则都满足,则ret为true,只要有一条不满足,ret就为false。
        ret = obj.is_valid()

#obj.clean()就是获取到的用户输入信息
        if ret:
            print(obj.clean())
        else:

#obj.errors,获取错误信息。
            print(obj.errors)
    return render(request,login.html)

 

templates→login.html,

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div>
        <input type="text" name="user" />
    </div>

    <div>
        <input type="password" name="pwd" />
    </div>

    <input type="button" value=http://www.mamicode.com/"login" onclick="OnSubmit()"/>

    <script src=http://www.mamicode.com/"/static/js/jquery-1.12.4.js" ></script>
    <script>

        function OnSubmit(){
            var info_dict = {};
            $(input).each(function(){

#将name值作为键,value值作为值,加入到字典。
                var v = $(this).val();
                var n = $(this).attr(name);
                info_dict[n] = v;
            });


            $.ajax({
            url : /login/,
            type : POST,
            data : info_dict ,
            success:function(data){

            },
            error:function(data){

            }
        })
        }


    </script>
</body>
</html>

如果用户名密码都为空时点登陆,则obj.errors信息见下:

<ul class="errorlist"><li>pwd<ul class="errorlist"><li>This field is required.</li></ul></li><li>user<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
#提示用户名密码都是被要求的

如果用户名为空,密码不为空时点登陆,则obj.errors信息见下:

<ul class="errorlist"><li>user<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
#提示用户名是被要求的

如果都不为空,则obj.clean()信息见下:

{pwd: 123, user: 123}
#都不为空,也就不报错了,直接获取到用户输入的内容。

 

1217