Form表单——例子

<div id="cnblogs_post_body">

Form

Form的验证思路

前端:form表单

后台:创建form类,当请求到来时,先匹配,匹配出正确和错误信息。

Django的Form验证实例

创建project,进行基础配置文件配置

STATIC_URL = =

<div class="cnblogs_code" onclick="cnblogs_code_show('b5aa4bda-c71e-4593-9376-340a349552cc')">


<div id="cnblogs_code_open_b5aa4bda-c71e-4593-9376-340a349552cc" class="cnblogs_code_hide">

MIDDLEWARE =
    

<div class="cnblogs_code" onclick="cnblogs_code_show('f51c2778-18b3-4626-ae7a-dd911ef4c9f1')">


<div id="cnblogs_code_open_f51c2778-18b3-4626-ae7a-dd911ef4c9f1" class="cnblogs_code_hide">

<div class="cnblogs_code" onclick="cnblogs_code_show('634cc90a-b528-4b4f-9225-ddc2dcd596cc')">


<div id="cnblogs_code_open_634cc90a-b528-4b4f-9225-ddc2dcd596cc" class="cnblogs_code_hide">

 django.conf.urls  django.contrib  app01.views urlpatterns =<span style="color: #000000;"> [
url(r
<span style="color: #800000;">'
<span style="color: #800000;">^admin/
<span style="color: #800000;">'
<span style="color: #000000;">,admin.site.urls),url(r
<span style="color: #800000;">'
<span style="color: #800000;">^form1/
<span style="color: #800000;">'
<span style="color: #000000;">,account.form1),<span style="color: #008000;">#<span style="color: #008000;"> url(r'^test/',account.test),
]

views.account.py:

 django.shortcuts  app01.forms <span style="color: #0000ff;">def<span style="color: #000000;"> form1(request):
<span style="color: #0000ff;">if
request.method==<span style="color: #800000;">"
<span style="color: #800000;">POST
<span style="color: #800000;">": <span style="color: #008000;">#<span style="color: #008000;">这里POST一定要大写
<span style="color: #008000;">#<span style="color: #008000;">通常获取请求信息
<span style="color: #008000;">#<span style="color: #008000;">request.POST.get("user",None)
<span style="color: #008000;">#<span style="color: #008000;">request.POST.get("pwd",None)
<span style="color: #008000;">#<span style="color: #008000;">获取请求内容,做验证
f = Form1(request.POST) <span style="color: #008000;">#<span style="color: #008000;">request.POST:将接收到的数据通过Form1验证
<span style="color: #0000ff;">if f.is_valid(): <span style="color: #008000;">#<span style="color: #008000;">验证请求的内容和Form1里面的是否验证通过。通过是True,否则False。
<span style="color: #0000ff;">print(f.cleaned_data) <span style="color: #008000;">#<span style="color: #008000;">cleaned_data类型是字典,里面是提交成功后的信息
<span style="color: #0000ff;">else: <span style="color: #008000;">#<span style="color: #008000;">错误信息包含是否为空,或者符合正则表达式的规则
<span style="color: #0000ff;">print(type(f.errors),f.errors) <span style="color: #008000;">#<span style="color: #008000;">errors类型是ErrorDict,里面是ul,li标签
<span style="color: #0000ff;">return render(request,<span style="color: #800000;">"<span style="color: #800000;">account/form1.html<span style="color: #800000;">",{<span style="color: #800000;">"<span style="color: #800000;">error<span style="color: #800000;">"<span style="color: #000000;">:f.errors})
<span style="color: #0000ff;">return render(request,<span style="color: #800000;">"<span style="color: #800000;">account/form1.html<span style="color: #800000;">")

<div class="cnblogs_code_toolbar"><span class="cnblogs_code_copy"><a title="复制代码" onclick="copyCnblogsCode(this)" href="javascript:void(0);">复制代码

html:


        
             
        
        
             
        
        
             
        
    

forms.py:

django <span style="color: #0000ff;">class<span style="color: #000000;"> Form1(forms.Form):
user
=<span style="color: #000000;"> forms.CharField()
pwd = forms.CharField()

访问页面:

没有输入内容后提交,通过模板语言展示了错误信息

Django强大之form验证时不用自定义错误信息就可以返回错误信息到前端以标签方式展现。

.is_valid():返回True或者False

.cleaned_data:通过验证后的数据

errors:
.error.get("user",None)error封装所有的错误信息,如果没有获取到,默认为None。

如:

.error.get["pwd"]直接获取到ul、li。

如:

Form之精华版本

forms.py

django <span style="color: #0000ff;">class<span style="color: #000000;"> Form1(forms.Form):
user
=<span style="color: #000000;"> forms.CharField()
pwd = forms.CharField()

HTML:

   
        {{ error.user.0 }}
        {{ error.pwd.0 }}
        
             
        
    

account.py

 request.method == = render(request,{:f.errors,
        f = render(request,{ render(request,)

注:

页面展示:

注:这里的是后端返回form对象到前端通过所创建的

更强大的功能:

forms里面的字段:

required:是否可以为空。required=True 不可以为空,required==4=2={: ,: =forms.TextInput(attrs={: =forms.Textarea()  生成Textarea标签。widget默认生成input标签

实战:

models.py

 django.db <span style="color: #008000;">#<span style="color: #008000;"> Create your models here.
<span style="color: #0000ff;">class<span style="color: #000000;"> Author(models.Model):
<span style="color: #800000;">"""<span style="color: #800000;">
作者
<span style="color: #800000;">"""<span style="color: #000000;">
name = models.CharField(max_length=100<span style="color: #000000;">)
age =<span style="color: #000000;"> models.IntegerField()

<span style="color: #0000ff;">class<span style="color: #000000;"> BookType(models.Model):
<span style="color: #800000;">"""<span style="color: #800000;">
图书类型
<span style="color: #800000;">"""<span style="color: #000000;">
caption = models.CharField(max_length=64<span style="color: #000000;">)

<span style="color: #0000ff;">class<span style="color: #000000;"> Book(models.Model):
<span style="color: #800000;">"""<span style="color: #800000;">
图书
<span style="color: #800000;">"""<span style="color: #000000;">
name = models.CharField(max_length=64<span style="color: #000000;">)
pages =<span style="color: #000000;"> models.IntegerField()
price = models.DecimalField(max_digits=10,decimal_places=2<span style="color: #000000;">)
pubdate =<span style="color: #000000;"> models.DateField()

authors </span>=<span style="color: #000000;"&gt; models.ManyToManyField(Author)
book_type </span>= models.ForeignKey(BookType)</pre>

<div class="cnblogs_code_toolbar"><span class="cnblogs_code_copy"><a title="复制代码" onclick="copyCnblogsCode(this)" href="javascript:void(0);">复制代码

forms.py:

 django  app01 <span style="color: #0000ff;">class<span style="color: #000000;"> Form1(forms.Form):
user
=<span style="color: #000000;"> forms.CharField(
widget
=forms.TextInput(attrs={<span style="color: #800000;">'
<span style="color: #800000;">class
<span style="color: #800000;">': <span style="color: #800000;">'<span style="color: #800000;">c1<span style="color: #800000;">'<span style="color: #000000;">}),error_messages={<span style="color: #800000;">'<span style="color: #800000;">required<span style="color: #800000;">': <span style="color: #800000;">'<span style="color: #800000;">用户名不能为空<span style="color: #800000;">'<span style="color: #000000;">},)
pwd = forms.CharField(max_length=4,min_length=2,required=<span style="color: #000000;">True)
email = forms.EmailField(error_messages={<span style="color: #800000;">'<span style="color: #800000;">required<span style="color: #800000;">': <span style="color: #800000;">'<span style="color: #800000;">邮箱不能为空<span style="color: #800000;">',<span style="color: #800000;">'<span style="color: #800000;">invalid<span style="color: #800000;">': <span style="color: #800000;">'<span style="color: #800000;">邮箱格式错误<span style="color: #800000;">'<span style="color: #000000;">})

memo </span>=<span style="color: #000000;"&gt; forms.CharField(
    widget</span>=<span style="color: #000000;"&gt;forms.Textarea()
)
</span><span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;直接写数据</span>
<span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; user_type_choice = (</span>
<span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;     (0,'普通用户'),</span>
<span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;     (1,'高级用户'),</span>
<span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; )</span>
<span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;通过BookType表查询信息,values_list拿到的是元组。id作为value显示,caption作为text在页面显示</span>
<span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; user_type_choice = models.BookType.objects.values_list('id','caption')</span>
<span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; book_type = forms.CharField(</span>
<span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;     widget=forms.widgets.Select(choices=user_type_choice,attrs={'class': "form-control"}))</span>


<span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;写上以下代码就不用担心数据库添加了数据而不能及时获取了</span>
<span style="color: #0000ff;"&gt;def</span> <span style="color: #800080;"&gt;__init__</span>(self,*args,**<span style="color: #000000;"&gt;kwargs):
    </span><span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;每次创建Form1对象时执行init方法</span>
    super(Form1,self).<span style="color: #800080;"&gt;__init__</span>(*args,**<span style="color: #000000;"&gt;kwargs)

    self.fields[</span><span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;book_type</span><span style="color: #800000;"&gt;'</span>] =<span style="color: #000000;"&gt; forms.CharField(
        widget</span>=forms.widgets.Select(choices=models.BookType.objects.values_list(<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;id</span><span style="color: #800000;"&gt;'</span>,<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;caption</span><span style="color: #800000;"&gt;'</span><span style="color: #000000;"&gt;),attrs</span>={<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;class</span><span style="color: #800000;"&gt;'</span>: <span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;form-control</span><span style="color: #800000;"&gt;"</span>}))</pre>

<div class="cnblogs_code_toolbar"><span class="cnblogs_code_copy"><a title="复制代码" onclick="copyCnblogsCode(this)" href="javascript:void(0);">复制代码

HTML:




    
    Title
    
        
        
        
    


    
        {{ error.user.0 }}
        {{ error.pwd.0 }}
        {{ error.email.0 }}
         {{ error.memo.0 }}
             {{ error.book_type.0 }}
    <span style="color: #0000ff;"&gt;<</span><span style="color: #800000;"&gt;div</span><span style="color: #0000ff;"&gt;></span>
        <span style="color: #0000ff;"&gt;<</span><span style="color: #800000;"&gt;input </span><span style="color: #ff0000;"&gt;type</span><span style="color: #0000ff;"&gt;="submit"</span><span style="color: #ff0000;"&gt; value</span><span style="color: #0000ff;"&gt;="提交"</span> <span style="color: #0000ff;"&gt;/></span>
    <span style="color: #0000ff;"&gt;</</span><span style="color: #800000;"&gt;div</span><span style="color: #0000ff;"&gt;></span>
<span style="color: #0000ff;"&gt;</</span><span style="color: #800000;"&gt;form</span><span style="color: #0000ff;"&gt;></span>

<span style="color: #0000ff;"></<span style="color: #800000;">body<span style="color: #0000ff;">>
<span style="color: #0000ff;"></<span style="color: #800000;">html<span style="color: #0000ff;">>


<div class="cnblogs_code_toolbar"><span class="cnblogs_code_copy"><a title="复制代码" onclick="copyCnblogsCode(this)" href="javascript:void(0);">复制代码

account.py:

 django.shortcuts  app01.forms  app01.models  *

<span style="color: #008000;">#<span style="color: #008000;"> def test(req):<span style="color: #008000;">

<span style="color: #008000;"> BookType.objects.create(caption='技术')<span style="color: #008000;">

<span style="color: #008000;"> BookType.objects.create(caption='文学')<span style="color: #008000;">

<span style="color: #008000;"> BookType.objects.create(caption='动漫')<span style="color: #008000;">

<span style="color: #008000;"> BookType.objects.create(caption='男人装')<span style="color: #008000;">

<span style="color: #008000;"> return HttpResponse("ok")

<span style="color: #0000ff;">def<span style="color: #000000;"> form1(request):
<span style="color: #0000ff;">if request.method == <span style="color: #800000;">"<span style="color: #800000;">POST<span style="color: #800000;">"<span style="color: #000000;">:
f =<span style="color: #000000;"> Form1(request.POST)
<span style="color: #0000ff;">if<span style="color: #000000;"> f.is_valid():
<span style="color: #0000ff;">print<span style="color: #000000;">(f.cleaned_data)
<span style="color: #0000ff;">else<span style="color: #000000;">:
<span style="color: #0000ff;">return render(request,<span style="color: #800000;">"<span style="color: #800000;">account/form1.html<span style="color: #800000;">")


<div class="cnblogs_code_toolbar"><span class="cnblogs_code_copy"><a title="复制代码" onclick="copyCnblogsCode(this)" href="javascript:void(0);">复制代码

Django里面没有手机验证,没有的需要自定义

示例:

django django.core.exceptions <span style="color: #0000ff;">def<span style="color: #000000;"> mobile_validate(value):
mobile_re
= re.compile(r<span style="color: #800000;">'
<span style="color: #800000;">^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$
<span style="color: #800000;">'
<span style="color: #000000;">)
<span style="color: #0000ff;">if
<span style="color: #0000ff;">not
<span style="color: #000000;"> mobile_re.match(value):
<span style="color: #0000ff;">raise
ValidationError(<span style="color: #800000;">'
<span style="color: #800000;">手机号码格式错误<span style="color: #800000;">'<span style="color: #000000;">)

<span style="color: #0000ff;">class<span style="color: #000000;"> PublishForm(forms.Form):

user_type_choice </span>=<span style="color: #000000;"&gt; (
    (0,u</span><span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;普通用户</span><span style="color: #800000;"&gt;'</span><span style="color: #000000;"&gt;),(</span>1,u<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;高级用户</span><span style="color: #800000;"&gt;'</span><span style="color: #000000;"&gt;),)

user_type </span>= forms.IntegerField(widget=forms.widgets.Select(choices=<span style="color: #000000;"&gt;user_type_choice,attrs</span>={<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;class</span><span style="color: #800000;"&gt;'</span>: <span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;form-control</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;}))

title </span>= forms.CharField(max_length=20<span style="color: #000000;"&gt;,min_length</span>=5<span style="color: #000000;"&gt;,error_messages</span>={<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;required</span><span style="color: #800000;"&gt;'</span>: u<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;标题不能为空</span><span style="color: #800000;"&gt;'</span><span style="color: #000000;"&gt;,</span><span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;min_length</span><span style="color: #800000;"&gt;'</span>: u<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;标题最少为5个字符</span><span style="color: #800000;"&gt;'</span><span style="color: #000000;"&gt;,</span><span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;max_length</span><span style="color: #800000;"&gt;'</span>: u<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;标题最多为20个字符</span><span style="color: #800000;"&gt;'</span><span style="color: #000000;"&gt;},widget</span>=forms.TextInput(attrs={<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;class</span><span style="color: #800000;"&gt;'</span>: <span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;form-control</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;,</span><span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;placeholder</span><span style="color: #800000;"&gt;'</span>: u<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;标题5-20个字符</span><span style="color: #800000;"&gt;'</span><span style="color: #000000;"&gt;}))

memo </span>= forms.CharField(required=<span style="color: #000000;"&gt;False,max_length</span>=256<span style="color: #000000;"&gt;,widget</span>=forms.widgets.Textarea(attrs={<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;class</span><span style="color: #800000;"&gt;'</span>: <span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;form-control no-radius</span><span style="color: #800000;"&gt;"</span>,<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;placeholder</span><span style="color: #800000;"&gt;'</span>: u<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;详细描述</span><span style="color: #800000;"&gt;'</span>,<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;rows</span><span style="color: #800000;"&gt;'</span>: 3<span style="color: #000000;"&gt;}))

phone </span>= forms.CharField(validators=<span style="color: #000000;"&gt;[mobile_validate,],error_messages</span>={<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;required</span><span style="color: #800000;"&gt;'</span>: u<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;手机不能为空</span><span style="color: #800000;"&gt;'</span><span style="color: #000000;"&gt;},</span><span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;placeholder</span><span style="color: #800000;"&gt;'</span>: u<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;手机号码</span><span style="color: #800000;"&gt;'</span><span style="color: #000000;"&gt;}))

email </span>= forms.EmailField(required=<span style="color: #000000;"&gt;False,error_messages</span>={<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;required</span><span style="color: #800000;"&gt;'</span>: u<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;邮箱不能为空</span><span style="color: #800000;"&gt;'</span>,<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;invalid</span><span style="color: #800000;"&gt;'</span>: u<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;邮箱格式错误</span><span style="color: #800000;"&gt;'</span><span style="color: #000000;"&gt;},widget</span>=forms.TextInput(attrs={<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;class</span><span style="color: #800000;"&gt;'</span>: <span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;form-control</span><span style="color: #800000;"&gt;"</span>,<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;placeholder</span><span style="color: #800000;"&gt;'</span>: u<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;邮箱</span><span style="color: #800000;"&gt;'</span>}))</pre>

= {: False,: ,: ,: request.method == ==] ==] = HttpResponse(json.dumps(ret))

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


注:所有源代码均实测运行过。所有源代码均已上传CSDN,请有需要的朋友自行下载。
继承APIView和ViewSetMixin;作用也与APIView基本类似,提供了身份认证、权限校验、流量管理等。ViewSet在开发接口中不经常用。
一、Django介绍Python下有许多款不同的 Web 框架。Django是重量级选手中最有代表性的一位。许多成功的网站和APP都基于Django。Django 是一个开放源代码的 Web 应用框架,由 Python 写成。Django 遵守 BSD 版权,初次发布于 2005 年 7 月, 并于 2008 年 9 月发布了第一个正式版本 1.0 。Django学习线路Django 采用了 MVT 的软件设计模式,即模型(Model),视图(View)和模板(Template)。这个MVT模式并
本文从nginx快速掌握到使用,gunicorn快速掌握到使用,实现小白快速搭建django项目,并对可能出现的报错进行了分析
uniapp微信小程序订阅消息发送服务通知
Django终端打印SQL语句 1 Setting配置: 2 默认python 使用的MysqlDB连接,Python3 支持支持pymysql 所有需要在app里面的__init__加上下面配置:
url: re_path(&#39;authors/$&#39;, views.AuthorView.as_view()), re_path(&#39;book/(?P\d+)/$&#39;, vie
前提 关于html寻找路线: template 如果在各个APP中存在, Django 会优先找全局template 文件下的html文件,如果全局下的template文件没有相关的html Djan
// GET请求request.GET // POST请求request.POST // 处理文件上传请求request.FILES // 处理如checkbox等多选 接受列表request.get
from bs4 import BeautifulSoup#kindeditordef kindeditor(request): s = &#39;&#39;&#39; &lt;li&gt;&lt;s
view.py 配置 html 配置
from django.http import JsonResponse JsonResponse 里面代码会加这一个响应头 kwargs.setdefault(&#39;content_type&#
#下面两种是基于QuerySet查询 也就是说SQL中用的jion连表的方式查询books = models.UserInfo.objects.all() print(type(books)) &gt
return HttpResponse(&quot;OK&quot;) 返回一个字符串 return redirect(&quot;/index/&quot;) 返回URL return render
from django.http import JsonResponse JsonResponse 里面代码会加这一个响应头 kwargs.setdefault(&#39;content_type&#
浏览器有一个很重要的概念——同源策略(Same-Origin Policy)。所谓同源是指,域名,协议,端口相同。不同源的客户端脚本(javascript、ActionScript)在没明确授权的情况
自动发送 &gt; 依赖jQuery文件 实例--&gt;GET请求: 手动发送 &gt; 依赖浏览器XML对象(也叫原生ajax) Ajax主要就是使用 【XmlHttpRequest】对象来完成请
#下面两种是基于QuerySet查询 也就是说SQL中用的jion连表的方式查询books = models.UserInfo.objects.all() print(type(books)) &gt
// GET请求request.GET // POST请求request.POST // 处理文件上传请求request.FILES // 处理如checkbox等多选 接受列表request.get
return HttpResponse(&quot;OK&quot;) 返回一个字符串 return redirect(&quot;/index/&quot;) 返回URL return render