django_Form组件

views文件

from django.shortcuts import render,HttpResponse,redirect

# Create your views here.
from django import forms
from django.forms import fields

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

    pwd=fields.CharField(min_length=12,
                         required=True,
                         error_messages={'required': '用户名不能为空', 'max_length': '太长了', 'min_length': '太短了',
                                         'invalid': '..'}
                         )

    email=fields.EmailField(
        required=True,
        min_length=8,
        error_messages={"required":'邮箱不能为空','invalid':'邮箱格式错误'})

    age=fields.IntegerField(
        required=True,
        error_messages={"required":'年龄不能为空','invalid':'年龄必须为数字'}                    )

def f1(request):
    if request.method=="GET":
        obj=F1Form() #用来给前端添加html
        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})

 

 

html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<form id = 'fm' action="" method="post">
    <p>{{ obj.user }}{{ obj.errors.user.0 }}</p>
    <p>{{ obj.pwd }}{{ obj.errors.pwd.0 }}</p>
    <p>{{ obj.email }}{{ obj.errors.email.0 }}</p>
    <p>{{ obj.age }}{{ obj.errors.age.0 }}</p>
    <input type="submit" value="提交">
    <input type="button" value="ajax" onclick="submitAjaxForm()">

</form>



</body>
</html>

 

posted @ 2018-06-14 07:40  阜阳小全  阅读(120)  评论(0编辑  收藏  举报