django from表单验证

实现:表单验证

工程示例:

urls.py

from django.conf.urls import url
from django.contrib import admin
from app01 import views


urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^f1.html$', views.f1),
]

settings.py

STATIC_FILES_DIRS = (
    os.path.join(BASE_DIR,'static'),
)

views.py

from django.shortcuts import render
from django.shortcuts import redirect
from django.shortcuts import HttpResponse
from app01 import models

from django import forms
from django.forms import fields


class F1Form(forms.Form):
    user = fields.CharField(
        max_length=18,
        min_length=6,
        required=True,
        error_messages={'required': '用户名不能为空',
                        'max_length': '太长了',
                        'min_length': '太短了'
                        }
    )

    pwd = fields.CharField(
        required=True,
        min_length=32
    )

    age = fields.IntegerField(
        required=True,
        error_messages={
            'required': '邮箱不能为空',
            'invalid': '邮箱格式错误',
        }
    )

    email = fields.EmailField(
        required=True,
        min_length=8
    )


def f1(request):
    if request.method == 'GET':
        obj = F1Form()
        return render(request, 'f1.html', {'obj': obj})
    else:
        obj = F1Form(request.POST)
        # 是否全部验证成功
        if obj.is_valid():
            # 用户提交的数据
            print('验证成功', obj.cleaned_data)
            return redirect('http://www.baidu.com')
        else:
            print('验证失败', obj.errors)
            return render(request, 'f1.html', {'obj': obj})

f1.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form id="fm" action="/f1.html" method="POST">
    <p>用户{{ obj.user }}{{ obj.errors.user.0 }}</p>
    <p>密码{{ obj.pwd }}{{ obj.errors.pwd.0 }}</p>
    <p>年龄{{ obj.age }}{{ obj.errors.age.0 }}</p>
    <p>邮箱{{ obj.email }}{{ obj.errors.email.0 }}</p>
    <input type="submit" value="提交" />
</form>
<script src="/static/js/jquery-3.1.1.js"></script>

</body>
</html>

 注意事项:

posted @ 2017-03-15 21:18  努力哥  阅读(306)  评论(0编辑  收藏  举报