form 表单基本功能

form组件

1,对用户信息验证

-Ajax

-Form

2.生成HTML代码

3.创建一个类

类中创建字段(含正则表达式)

GET

  obj=FiForm()

  obj.user=>自动生成HTML

POST

obj=FIForm(request.POST)

if obj.is_valid():

  obj.cleaned_data

else:

  obj.errors

 
  
from django.shortcuts import render
from django.shortcuts import redirect


from django import forms
from django.forms import fields





#创建form类 当请求到来时,先匹配,匹配出正确和错误信息。
class FlForm(forms.Form):
    user=fields.CharField(
        max_length=23,
        min_length=8,
        required=True,
        error_messages={
            'max_length':'长了',
            'min_length':'短了',
            'required':'格式错误'
        }
    )
    pwd=fields.CharField(
        min_length=12,
        required=True,
        error_messages={
            'min_length': '短了',
            'required': '格式错误'
        }

    )
    age=fields.CharField(
        required=True,
        error_messages={
            'required': '格式错误',
            'invalid':'必须为数字'
        }
    )
    email=fields.CharField(
        required=True,
        min_length=6,
        error_messages={
            'required':'邮箱不能为空',
            'min_length': '短了',
            'invalid': '邮箱格式错误'
        }
    )


def f1(request):
    if request.method=='GET':
        obj=FlForm()

        return render(request,'f1.html',{'obj':obj})
    else:
        # u=request.POST.get('user')
        # p=request.POST.get('pwd')
        # e=request.POST.get('email')
        # a = request.POST.get('age')
        obj=FlForm(request.POST)
        v=obj.is_valid()#验证是否匹配成功
        if v:
            print('验证成功',obj.cleaned_data)

            return redirect('http://www.xiaohuar.com')
        else:
            print('验证失败',obj.errors)
            return render(request, 'f1.html',{'obj':obj})
View Code
 
  
HTML代码

"en">

    "UTF-8">
    Title



"fm" action="/f1.html" method="POST">

{{obj.user}}{{ obj.errors.user.0 }}

{{obj.pwd}} {{ obj.errors.pwd.0 }}

{{obj.email}}{{ obj.errors.email.0}}

{{obj.age}}{{ obj.errors.age.0}}

"submit" value="提交"/>

"button" value="Ajax提交" onclick="submitAjaxFrom()"/>

View Code
 
  

 

 

 

你可能感兴趣的:(form 表单基本功能)