Django中的Form

Form

 

1、使用Form

Django中的Form使用時通常有兩種功能:javascript

一、生成html標籤html

二、驗證輸入內容前端

要想使用django提供的form,要在views裏導入form模塊java

  from django import formspython

而後再定義一個類,這個類就是要在前端html頁面中生成form表單中的input標籤的。jquery

1 class UserInfo(forms.Form): 2     email = forms.EmailField() 3     host = forms.CharField() 4     port = forms.CharField() 5     mobile = forms.CharField()

 

 

自定義From的流程:ajax

 

2、多說無益,直接看代碼:

 1 # coding:utf-8
 2 
 3 
 4 from django import forms  5 
 6 class UserInfo(forms.Form): #定義的django表單  7     email = forms.EmailField()  8     host = forms.CharField()  9     port = forms.CharField() 10     mobile = forms.CharField() 11 
12 def user_list(request): 13 
14     obj =UserInfo()           #建立form的對象 15     if request.method == "POST": 16         user_input_obj = UserInfo(request.POST)    #request.POST爲提交過來的全部數據
17 
18         if user_input_obj.is_valid():      #is_valid判斷輸入的內容是否合法 Ture 或False
19             data = user_input_obj.clean()      #.clen()獲取提交的數據
20 
21             host_name = data['host'] 22             print data 23             print host_name 24         else:                   #若是輸入不合法,返回錯誤信息
25             error_msg = user_input_obj.errors      #errors爲錯誤信息
26             return  render(request,'user_list.html',{'obj':user_input_obj,'errors':error_msg}) 27             #將錯誤信息直接返回到前端頁面去展現
28     return  render(request,'user_list.html',{'obj':obj})

 

前端html頁面:django

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title></title>
 6 </head>
 7 <body>
 8 
 9     <form action="/user_list/" method="post">
10         <p>主機:{{ obj.host }} <span>{{ errors.host }}</span></p>
11         <p>端口::{{ obj.port }} <span>{{ errors.port }}</span></p>
12         <p>郵箱::{{ obj.email }} <span>{{ errors.email }}</span></p>
13         <p>手機:{{ obj.mobile }} <span>{{ errors.mobile }}</span></p>
14         <input type="submit" value="submit">
15 
16     </form>
17 
18 </body>
19 </html>

 

 

3、自定義Form

一、自定義錯誤提示信息json

  • error_messages={'required': u'手機不能爲空'},

 

1 class UserInfo(forms.Form): 2     email = forms.EmailField(error_messages={'required': u'郵箱不能爲空'},) 3     host = forms.CharField(error_messages={'required': u'主機不能爲空'},) 4     port = forms.CharField(error_messages={'required': u'端口不能爲空'},) 5     mobile = forms.CharField(error_messages={'required': u'手機不能爲空'},)

 

 

二、自定義Form的樣式屬性app

  • widget=forms.TextInput(attrs={'class': "form-control",
    'placeholder': u'手機號碼'}),
 1 class UserInfo(forms.Form):  2 email = forms.EmailField(error_messages={'required': u'郵箱不能爲空'},)  3 host = forms.CharField(error_messages={'required': u'主機不能爲空'},)  4 port = forms.CharField(error_messages={'required': u'端口不能爲空'},)  5 mobile = forms.CharField(error_messages={'required': u'手機不能爲空'},  6  widget=forms.TextInput(attrs={'class': "form-control",  7 'placeholder': u'手機號碼'}),)  8  9 memo = forms.CharField(required=False, #默認輸入能夠爲空 10 widget=forms.Textarea(attrs={'class':"form-control", 11 'placeholder':u"備註"}))

 

 

三、自定義驗證Form表單中的內容是否合法:

  • validators=[mobile_validate, ],
 1 from django.core.exceptions import ValidationError  2 import re  3 
 4 
 5 def mobile_validate(value):  6     mobile_re = re.compile(r'^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$')  7     if not mobile_re.match(value):  8         raise ValidationError('手機號碼格式錯誤')  9 
10 
11 class UserInfo(forms.Form): 12     email = forms.EmailField(error_messages={'required': u'郵箱不能爲空'},) 13     host = forms.CharField(error_messages={'required': u'主機不能爲空'},) 14     port = forms.CharField(error_messages={'required': u'端口不能爲空'},) 15     mobile = forms.CharField(validators=[mobile_validate, ], 16                              error_messages={'required': u'手機不能爲空'}, 17                              widget=forms.TextInput(attrs={'class': "form-control", 18                                                           'placeholder': u'手機號碼'}),) 19 
20     memo = forms.CharField(required=False,  #默認輸入能夠爲空
21                            widget=forms.Textarea(attrs={'class':"form-control", 22                                                         'placeholder':u"備註"}))

 

 

 四、自定義Form中的select

 1 class UserInfo(forms.Form):  2     
 3     
 4    user_type_choice = (  5         (0, u'普通用戶'),  6         (1, u'高級用戶'),  7  )  8     user_type = forms.IntegerField(widget=forms.widgets.Select(choices=user_type_choice,  9                                                                attrs={'class': "form-control"})) 10     
11     email = forms.EmailField(error_messages={'required': u'郵箱不能爲空'},) 12     host = forms.CharField(error_messages={'required': u'主機不能爲空'},) 13     port = forms.CharField(error_messages={'required': u'端口不能爲空'},) 14     mobile = forms.CharField(validators=[mobile_validate, ], 15                              error_messages={'required': u'手機不能爲空'}, 16                              widget=forms.TextInput(attrs={'class': "form-control", 17                                                           'placeholder': u'手機號碼'}),) 18 
19     memo = forms.CharField(required=False,  #默認輸入能夠爲空
20                            widget=forms.Textarea(attrs={'class':"form-control", 21                                                         'placeholder':u"備註"}))

 

 

五、自定義錯誤信息的樣式

一、Form錯誤信息:

若是不作任何處理,錯誤信息的顯示會有一個默認<ul>的樣式,咱們能夠把它去掉,在錯誤信息的後面添加 as_data(),顯示原始的數據。

  • user_input_obj.errors.as_data()

僅這樣作還不夠,還須要在前端頁面標籤中取出錯誤信息。但模板語言不支持索引的取值方式,因此這裏還須要與python的結合

在app的目錄下建立一個templatetags目錄,而後建立一個py文件,取名爲form_tag.py

 1 #!/usr/bin/env python  2 # -*- coding:utf-8 -*-  3  4 from django import template  5  6 register = template.Library()  7  8 @register.simple_tag  9 def error_message(arg): 10 if arg: 11 return arg[0][0] 12 else: 13 return ''

 

 而後再前端頁面導入form_tag,並使用

 1 {% load form_tag %}  導入py文件  2 <!DOCTYPE html>
 3 <html lang="en">
 4 <head>
 5     <meta charset="UTF-8">
 6     <title></title>
 7 </head>
 8 <body>
 9 
10     <form action="/app01/user_list/" method="post">
11         <p>用戶類型:{{ obj.user_type }} <span>{{ errors.user_type }}</span></p>
12         <p>主機:{{ obj.host }} <span style="color: red;">{% error_message errors.host %} </span></p> 書寫方式有所改變
13         <p>端口::{{ obj.port }} <span>{{ errors.port }}</span></p>
14         <p>郵箱::{{ obj.email }} <span>{{ errors.email }}</span></p>
15         <p>手機:{{ obj.mobile }} <span>{{ errors.mobile }}</span></p>
16         <p>備註:{{ obj.memo }} <span>{{ errors.memo }}</span></p>
17         <input type="submit" value="submit">
18 
19     </form>
20 
21 </body>
22 </html>

 

 

二、Ajax錯誤信息:

  • user_input_obj.errors.as_json()

html文件:定義ajax

 

 1 {% load staticfiles %}  2 <!DOCTYPE html>  3 <html lang="en">  4 <head>  5 <meta charset="UTF-8">  6 <title></title>  7 </head>  8 <body>  9 10 <form action="/login/" method="post"> 11 <p>{{ obj.username }}</p> 12 <p>{{ obj.password }}</p> 13 <input type="submit" value="submit"> 14 <input type="button" onclick="Ajax();" value="Ajax"> 15 </form> 16 17 {#<script type="text/javascript" src="{{ STATIC_URL }}/js/jquery-2.1.4.min.js">#} 18 <script type="text/javascript" src="{% static "js/jquery-2.1.4.min.js" %}"></script> 19 <script> 20 function Ajax(){ 21  $.ajax({ 22  url:'/login/', 23  type:'POST', 24  data:{'username':'','password':''}, 25  success:function(arg){ 26  console.log(arg); 27  } 28  }) 29  } 30 </script> 31 </body> 32 </html>

 

後臺處理:

返回數據時,要用HttpResponse

 1 def login(request):  2  3 obj = Account_Forms.UserInfo(request.POST)  4 if request.method == 'POST':  5 if obj.is_valid():  6 data = obj.clean()  7 print data  8  9 else: 10 error_msg = obj.errors.as_json() 11 return HttpResponse(error_msg) #用HttpResponse的方式返回數據 12 return render(request, 'account/login.html', {'obj': obj}) 13 return render(request, 'account/login.html', {'obj': obj})

 

相關文章
相關標籤/搜索