欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Django框架 Form组件 实例

程序员文章站 2022-04-25 15:47:28
...

1.实例1:

#app01/views.py:

import re,json
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):#必须继承forms.Form
    user_type_choice=(
        (0,u'普通用户'),
        (1,u'高级用户'),
    )
    user_type=forms.IntegerField(
        widget=forms.widgets.Select(
            choices=user_type_choice,
            attrs={
                'class':"form-control"
            }
        )
    )
    title=forms.CharField(
    #字段应和对应的<input>的name属性的值相同
        max_length=20,#最大长度
        min_length=5,#最小长度
        required=True,#不能为空
        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'邮箱'
            }
        )
    )

def publish(request):
    ret={'status':False,'data':'','error':'','summary':''}
    if request.method=='POST':
        request_form=PublishForm(request.POST)#进行验证
        #对于<form>表单/Ajax这2种提交方式,都可以进行验证
        if request_form.is_valid():#如果验证成功(格式正确)
            #request_dict=request_form.clean()
            request_dict=request_form.cleaned_data
            #验证成功的数据,是个dict
            print(request_dict["email"])#打印email信息
            ret['status']=True
        else:
            error_msg=request_form.errors.as_json()
            #error_msg=request_form.errors
            #错误信息,类似1个dict
            #t_error_msg=request_form.errors.title
            #title字段的错误信息,类似1个list
            #t_error_msg.0表示第1条错误信息
            ret['error']=json.loads(error_msg)
    return HttpResponse(json.dumps(ret))

2.实例2:

#app01/views.py:

from django.shortcuts import render,HttpResponse,redirect
from django import forms

class UserForm(forms.Form):
    user=forms.fields.CharField(
    #每个字段对应1个验证规则,每个验证是1个正则表达式
        max_length=18,
        min_length=6,
        required=True
        error_messages={
            "required":"用户名不能为空",#为空时的错误提示
            "max_length":"用户名最长为18个字符",#过长时的错误提示
            "min_length":"用户名最短为6个字符"#过短时的错误提示
        }
    )
    pwd=forms.fields.CharField(
        required=True,
        min_length=12
        error_messages={
            "required":"密码不能为空",
            "min_length":"密码最短为6个字符"
        }
    )
    age=forms.fields.IntegerField(
        required=True
        error_messages={
            "required":"年龄不能为空",
            "invalid":"年龄格式错误"#格式不合法时的错误提示
        }
    )
    email=forms.fields.EmailField(
        required=True
        min_length=8,
        error_messages={
            "required":"邮箱不能为空",
            "min_length":"邮箱最短为8个字符",
            "invalid":"邮箱格式错误"
        }
    )

def user(req):
    user_list=models.UserInfo.objects.all()
    return render(req,"/user.html")

def add(req):
    if req.method=="POST":
        obj=UserForm(req.POST)
        if obj.is_valid():
            models.UserInfo.objects.create(**obj.cleaned_data)
            #将obj.cleaned_data直接作为字典传入,创建记录
            #注意应和数据库中的字段名相同
            return redirect("/user.html")
        else:
            return render(req,"/add.html",{"obj":obj})
    elif req.method="GET":
        info={"user":"请输入用户名","pwd":"请输入密码","age":"请输入年龄","email":"请输入邮箱"}
        obj=UserForm(**info)
        return render(req,"/add.html",{"obj":obj})

def edit(req,nid):
    if req.method=="GET":
	    data=models.UserInfo.objects.filter(id=nid).first()
	    obj=UserForm({"user":data.user,"email":data.email})
	    #传入的值将作为<input>的默认值
	    return render(req,"/user.html",{"obj":obj,"nid":nid})
    elif req.method=="POST":
        obj=UserForm(obj.POST)
        if obj.is_valid():
            models.UserInfo.objects.filter(id=nid).update(**obj.cleaned_data)
            return redirect("/user.html")
        else:
            return render(req,"/user.html",{"obj":obj,"nid":nid})
<!--user.html:-->

<body>
	<a href="/add.html">添加</a>
	<ul>
	    {% for row in user_list %}
	        <li>{{row.id}}-{{row.user}}-{{row.age}}-{{row.email}}-<a href="/edit.html-{{row.id}}">编辑</a></li>
        {% endfor %}
    <ul>
</body>
<!--add.html:-->

<body>
	<form action="/add.html.html">
	    <p>{{obj.user}}{{obj.errors.user.0}}</p><!--第1条错误信息-->
	    <!--{{obj.user}}将创建1个用于输入user的<input>
	    <!--<p><input type="text" name="user">{{obj.errors.user}}</p>-->
	    <!--上1条的效果见下图1,下1条的效果见下图2(仅是效果,并非本例实际结果)-->
	    <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>
</body>

Django框架 Form组件 实例
Django框架 Form组件 实例

<!--edit.html:-->

<body>
    <form action="/edit.html-{{nid}}" method="POST">
        {% csrf_token %}
        <p>{{obj.user}}{{obj.errors.user.0}}</p>
        <p>{{obj.email}}{{obj.errors.email.0}}</p>
        <input type="submit" value="提交">
    </form>
</body>

3.实例3:

#views.py:

from django.shortcuts import render,HttpResponse,redirect
from django import forms
import json

class AjaxForm(forms.Form):
    price=forms.fields.IntegerField()
    user_id=forms.fields.IntegerField(
        widget=forms.widgets.Select(choices=[(1,"aaa"),(2,"abc"),(3,"asd")])
    )

def ajax(req):
    if req.method=="GET":
        obj=AjaxForm()
        return render(req,"ajax.html",{"obj":obj})
    elif req.method=="POST":
        ret={"status":"N","message":None}
        obj=AjaxForm(req.POST)
        if obj.is_valid():#是在这1句进行的验证
			print(obj.cleaned_data)
			#return redirect("http://www.baidu.com")
			  #由于采用Ajax进行提交,这1句无效
			ret["status"]="Y"
			return HttpResponse(json.dumps(ret))
		else:
            print(obj.errors)
            ret["message"]=obj.errors
			return HttpResponse(json.dumps(ret))

#说明:
obj.errors的数据类型是ErrorDict,不是Python的基本数据类型
但是ErrorDict类继承dict,因此二者被序列化的方式相同
故虽然ErrorDict不是基本数据类型,但也能进行json.dumps()
<!--ajax.html:-->

<body>
    <form id="fm" method="POST" action="/ajax.html">
        {% csrf_token %}
        {{ obj.as_p }}
        <input type="button" value="Ajax提交" id="btn">
    </form>
    <script src="/static/jquery-3.1.1.js"></script>
    <script>
        $(function() {
            $("#btn").click(function() {
                $.ajax({
                    url:"/ajax.html",
                    type:"POST",
                    data:$("#fm").serialize(),
                    dataType:"JSON",
                    success:function(arg) {
                        //arg必须包含:验证结果,错误信息
                        if (arg.status=="Y") {
                            window.location.href="http://www.baidu.com"
                              //这1句用于跳转
                        }
                    }
                })
            })
        })
    </script>
</body>