欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Django中的forms組件實(shí)例詳解

 更新時(shí)間:2018年11月08日 14:33:51   作者:爬呀爬Xjm  
這篇文章主要介紹了Django的forms組件,本文通過實(shí)例代碼介紹了Django的forms組件,需要的朋友可以參考下

Form介紹

我們之前在HTML頁面中利用form表單向后端提交數(shù)據(jù)時(shí),都會寫一些獲取用戶輸入的標(biāo)簽并且用form標(biāo)簽把它們包起來。

與此同時(shí)我們在好多場景下都需要對用戶的輸入做校驗(yàn),比如校驗(yàn)用戶是否輸入,輸入的長度和格式等正不正確。如果用戶輸入的內(nèi)容有錯(cuò)誤就需要在頁面上相應(yīng)的位置顯示對應(yīng)的錯(cuò)誤信息.。

Django form組件就實(shí)現(xiàn)了上面所述的功能。

總結(jié)一下,其實(shí)form組件的主要功能如下:

  • 生成頁面可用的HTML標(biāo)簽
  • 對用戶提交的數(shù)據(jù)進(jìn)行校驗(yàn)
  • 保留上次輸入內(nèi)容

先在應(yīng)用目錄下my_forms.py定義好一個(gè)UserForm類

from django import forms
 from django.forms import widgets 
   class UserForm(forms.Form):
     username = forms.CharField(min_length=4, label='用戶名',
                   widget=widgets.TextInput(attrs={"class": "form-control"}),
                   error_messages={
                     "required": "用戶名不能為空",
                   })
     pwd = forms.CharField(min_length=4, label='密碼',
                error_messages={
                  "required": "密碼不能為空",
                },
                widget=widgets.PasswordInput(attrs={"class": "form-control"}))
     r_pwd = forms.CharField(min_length=4, label='確認(rèn)密碼',
                 widget=widgets.PasswordInput(attrs={"class": "form-control"}),
                 error_messages={
                   "required": "密碼不能為空",
                 })
     email = forms.EmailField(label='郵箱',
                 widget=widgets.EmailInput(attrs={"class": "form-control"}),
                 error_messages={
                   "required": '郵箱不能為空',
                   "invalid": "郵箱格式錯(cuò)誤",
                 })
     tel = forms.CharField(label='手機(jī)號',
                widget=widgets.TextInput(attrs={"class": "form-control"}),
                )

再寫一個(gè)視圖函數(shù):

  在寫一個(gè)視圖函數(shù)

   def reg(request):
     form = UserForm()
     if request.method == "POST":
       print(request.POST)
       # 實(shí)例化form對象的時(shí)候,把post提交過來的數(shù)據(jù)直接傳進(jìn)去
       form = UserForm(request.POST) # form表單的name屬性值應(yīng)該與forms組件的字段名稱一致
       if form.is_valid():
         print(form.cleaned_data)
         return HttpResponse('注冊成功')
     return render(request, 'reg.html', locals())

login.html

  <!DOCTYPE html>
   <html lang="zh_CN">
   <head>
     <meta charset="UTF-8">
     <meta http-equiv="x-ua-compatible" content="IE=edge">
     <meta name="viewport" content="width=device-width, initial-scale=1">
     <title>注冊</title>
   </head>
   <body>
   <h3>傳統(tǒng)form表單</h3>
   <form action="" method="post">
     {% csrf_token %}
     <p>用戶名:<input type="text" name="username"></p>
     <p>密碼:<input type="password" name="pwd"></p>
     <p>確認(rèn)密碼:<input type="password" name="r_pwd"></p>
     <p>郵箱:<input type="email" name="email"></p>
     <p>手機(jī)號:<input type="tel" name="tel"></p>
     <p><input type="submit" value="提交"></p>
   </form>
   <h3>forms組件渲染方式1</h3>
   <form action="" method="post" novalidate>
     {% csrf_token %}
     <p>{{ form.username.label }}:{{ form.username }} <span>{{ form.username.errors.0 }}</span></p>
     <p>密碼:{{ form.pwd }}
       <span>{{ form.pwd.errors.0 }}</span></p>
     <p>確認(rèn)密碼:{{ form.r_pwd }}
       <span>{{ form.r_pwd.errors.0 }}</span></p>
     <p>郵箱:{{ form.email }}
       <span>{{ form.email.errors.0 }}</span></p>
     <p>手機(jī)號:{{ form.tel }}
       <span>{{ form.tel.errors.0 }}</span></p>
     <p><input type="submit" value="提交"></p>
   </form>
   <h3>forms組件渲染標(biāo)簽方式2</h3>
     <form action="" method="post" novalidate>
       {% csrf_token %}
       {% for field in form %}
         <div class="form-group clearfix">
           <label for="">{{ field.label }}</label>
           {{ field }}
           <span style="color: red" class="pull-right">{{ field.errors.0 }}</span>
           {% if field.name == 'r_pwd' %}
             <span style="color: red" class="pull-right">{{ errors.0 }}</span>
           {% endif %}
         </div>
       {% endfor %}
       <input type="submit" value="注冊" class="btn btn-default pull-right">
     </form>
   <h3>forms組件渲染標(biāo)簽方式3  不推薦使用</h3>
   <form action="" method="post">
     {% csrf_token %}
     {{ form.as_p }}
     <input type="submit" value="注冊">
   </form>
   </body>
   </html>

看網(wǎng)頁效果發(fā)現(xiàn) 也驗(yàn)證了form的功能:

• 前端頁面是form類的對象生成的                                      -->生成HTML標(biāo)簽功能

• 當(dāng)用戶名和密碼輸入為空或輸錯(cuò)之后 頁面都會提示        -->用戶提交校驗(yàn)功能

• 當(dāng)用戶輸錯(cuò)之后 再次輸入 上次的內(nèi)容還保留在input框   -->保留上次輸入內(nèi)容

Form那些事兒

常用字段與插件

創(chuàng)建Form類時(shí),主要涉及到 【字段】 和 【插件】,字段用于對用戶請求數(shù)據(jù)的驗(yàn)證,插件用于自動(dòng)生成HTML;

initial

初始值,input框里面的初始值。

class LoginForm(forms.Form):
  username = forms.CharField(
    min_length=8,
    label="用戶名",
    initial="張三" # 設(shè)置默認(rèn)值
  )
  pwd = forms.CharField(min_length=6, label="密碼")

error_messages

重寫錯(cuò)誤信息。

class LoginForm(forms.Form):
  username = forms.CharField(
    min_length=8,
    label="用戶名",
    initial="張三",
    error_messages={
      "required": "不能為空",
      "invalid": "格式錯(cuò)誤",
      "min_length": "用戶名最短8位"
    }
  )
  pwd = forms.CharField(min_length=6, label="密碼")

password

class LoginForm(forms.Form):
  ...
  pwd = forms.CharField(
    min_length=6,
    label="密碼",
    widget=forms.widgets.PasswordInput(attrs={'class': 'c1'}, render_value=True)
  )

radioSelect

單radio值為字符串

class LoginForm(forms.Form):
  username = forms.CharField(
    min_length=8,
    label="用戶名",
    initial="張三",
    error_messages={
      "required": "不能為空",
      "invalid": "格式錯(cuò)誤",
      "min_length": "用戶名最短8位"
    }
  )
  pwd = forms.CharField(min_length=6, label="密碼")
  gender = forms.fields.ChoiceField(
    choices=((1, "男"), (2, "女"), (3, "保密")),
    label="性別",
    initial=3,
    widget=forms.widgets.RadioSelect()
  )

單選Select

class LoginForm(forms.Form):
  ...
  hobby = forms.fields.ChoiceField(
    choices=((1, "籃球"), (2, "足球"), (3, "雙色球"), ),
    label="愛好",
    initial=3,
    widget=forms.widgets.Select()
  )

多選Select

class LoginForm(forms.Form):
  ...
  hobby = forms.fields.MultipleChoiceField(
    choices=((1, "籃球"), (2, "足球"), (3, "雙色球"), ),
    label="愛好",
    initial=[1, 3],
    widget=forms.widgets.SelectMultiple()
  )

單選checkbox

class LoginForm(forms.Form):
  ...
  keep = forms.fields.ChoiceField(
    label="是否記住密碼",
    initial="checked",
    widget=forms.widgets.CheckboxInput()
  )

多選checkbox

class LoginForm(forms.Form):
  ...
  hobby = forms.fields.MultipleChoiceField(
    choices=((1, "籃球"), (2, "足球"), (3, "雙色球"),),
    label="愛好",
    initial=[1, 3],
    widget=forms.widgets.CheckboxSelectMultiple()
  )

關(guān)于choice的注意事項(xiàng):

在使用選擇標(biāo)簽時(shí),需要注意choices的選項(xiàng)可以從數(shù)據(jù)庫中獲取,但是由于是靜態(tài)字段 ***獲取的值無法實(shí)時(shí)更新***,那么需要自定義構(gòu)造方法從而達(dá)到此目的。

方式一:

from django.forms import Form
from django.forms import widgets
from django.forms import fields
 
class MyForm(Form):
  user = fields.ChoiceField(
    # choices=((1, '上海'), (2, '北京'),),
    initial=2,
    widget=widgets.Select
  )
  def __init__(self, *args, **kwargs):
    super(MyForm,self).__init__(*args, **kwargs)
    # self.fields['user'].choices = ((1, '上海'), (2, '北京'),)
    # 或
    self.fields['user'].choices = models.Classes.objects.all().values_list('id','caption')

方式二:

from django import forms
from django.forms import fields
from django.forms import models as form_model
class FInfo(forms.Form):
  authors = form_model.ModelMultipleChoiceField(queryset=models.NNewType.objects.all()) # 多選
  # authors = form_model.ModelChoiceField(queryset=models.NNewType.objects.all()) # 單選
Django Form所有內(nèi)置字段
Field
  required=True,        是否允許為空
  widget=None,         HTML插件
  label=None,         用于生成Label標(biāo)簽或顯示內(nèi)容
  initial=None,        初始值
  help_text='',        幫助信息(在標(biāo)簽旁邊顯示)
  error_messages=None,     錯(cuò)誤信息 {'required': '不能為空', 'invalid': '格式錯(cuò)誤'}
  validators=[],        自定義驗(yàn)證規(guī)則
  localize=False,       是否支持本地化
  disabled=False,       是否可以編輯
  label_suffix=None      Label內(nèi)容后綴
CharField(Field)
  max_length=None,       最大長度
  min_length=None,       最小長度
  strip=True          是否移除用戶輸入空白
IntegerField(Field)
  max_value=None,       最大值
  min_value=None,       最小值
FloatField(IntegerField)
  ...
DecimalField(IntegerField)
  max_value=None,       最大值
  min_value=None,       最小值
  max_digits=None,       總長度
  decimal_places=None,     小數(shù)位長度
BaseTemporalField(Field)
  input_formats=None     時(shí)間格式化  
DateField(BaseTemporalField)  格式:2015-09-01
TimeField(BaseTemporalField)  格式:11:12
DateTimeField(BaseTemporalField)格式:2015-09-01 11:12
DurationField(Field)      時(shí)間間隔:%d %H:%M:%S.%f
  ...
RegexField(CharField)
  regex,           自定制正則表達(dá)式
  max_length=None,      最大長度
  min_length=None,      最小長度
  error_message=None,     忽略,錯(cuò)誤信息使用 error_messages={'invalid': '...'}
EmailField(CharField)   
  ...
FileField(Field)
  allow_empty_file=False   是否允許空文件
ImageField(FileField)   
  ...
  注:需要PIL模塊,pip3 install Pillow
  以上兩個(gè)字典使用時(shí),需要注意兩點(diǎn):
    - form表單中 enctype="multipart/form-data"
    - view函數(shù)中 obj = MyForm(request.POST, request.FILES)
URLField(Field)
  ...
BooleanField(Field) 
  ...
NullBooleanField(BooleanField)
  ...
ChoiceField(Field)
  ...
  choices=(),        選項(xiàng),如:choices = ((0,'上海'),(1,'北京'),)
  required=True,       是否必填
  widget=None,        插件,默認(rèn)select插件
  label=None,        Label內(nèi)容
  initial=None,       初始值
  help_text='',       幫助提示
ModelChoiceField(ChoiceField)
  ...            django.forms.models.ModelChoiceField
  queryset,         # 查詢數(shù)據(jù)庫中的數(shù)據(jù)
  empty_label="---------",  # 默認(rèn)空顯示內(nèi)容
  to_field_name=None,    # HTML中value的值對應(yīng)的字段
  limit_choices_to=None   # ModelForm中對queryset二次篩選
ModelMultipleChoiceField(ModelChoiceField)
  ...            django.forms.models.ModelMultipleChoiceField
TypedChoiceField(ChoiceField)
  coerce = lambda val: val  對選中的值進(jìn)行一次轉(zhuǎn)換
  empty_value= ''      空值的默認(rèn)值
MultipleChoiceField(ChoiceField)
  ...
TypedMultipleChoiceField(MultipleChoiceField)
  coerce = lambda val: val  對選中的每一個(gè)值進(jìn)行一次轉(zhuǎn)換
  empty_value= ''      空值的默認(rèn)值
ComboField(Field)
  fields=()         使用多個(gè)驗(yàn)證,如下:即驗(yàn)證最大長度20,又驗(yàn)證郵箱格式
                fields.ComboField(fields=[fields.CharField(max_length=20), fields.EmailField(),])
MultiValueField(Field)
  PS: 抽象類,子類中可以實(shí)現(xiàn)聚合多個(gè)字典去匹配一個(gè)值,要配合MultiWidget使用
SplitDateTimeField(MultiValueField)
  input_date_formats=None,  格式列表:['%Y--%m--%d', '%m%d/%Y', '%m/%d/%y']
  input_time_formats=None  格式列表:['%H:%M:%S', '%H:%M:%S.%f', '%H:%M']
FilePathField(ChoiceField)   文件選項(xiàng),目錄下文件顯示在頁面中
  path,           文件夾路徑
  match=None,        正則匹配
  recursive=False,      遞歸下面的文件夾
  allow_files=True,     允許文件
  allow_folders=False,    允許文件夾
  required=True,
  widget=None,
  label=None,
  initial=None,
  help_text=''
GenericIPAddressField
  protocol='both',      both,ipv4,ipv6支持的IP格式
  unpack_ipv4=False     解析ipv4地址,如果是::ffff:192.0.2.1時(shí)候,可解析為192.0.2.1, PS:protocol必須為both才能啟用
SlugField(CharField)      數(shù)字,字母,下劃線,減號(連字符)
  ...
UUIDField(CharField)      uuid類型


Django Form內(nèi)置字段

校驗(yàn)

方式一:

from django.forms import Form
from django.forms import widgets
from django.forms import fields
from django.core.validators import RegexValidator
class MyForm(Form):
  user = fields.CharField(
    validators=[RegexValidator(r'^[0-9]+$', '請輸入數(shù)字'), RegexValidator(r'^159[0-9]+$', '數(shù)字必須以159開頭')],
  )

方式二:

import re
from django.forms import Form
from django.forms import widgets
from django.forms import fields
from django.core.exceptions import ValidationError
# 自定義驗(yàn)證規(guī)則
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('手機(jī)號碼格式錯(cuò)誤')
class PublishForm(Form):
  title = fields.CharField(max_length=20,
              min_length=5,
              error_messages={'required': '標(biāo)題不能為空',
                      'min_length': '標(biāo)題最少為5個(gè)字符',
                      'max_length': '標(biāo)題最多為20個(gè)字符'},
              widget=widgets.TextInput(attrs={'class': "form-control",
                             'placeholder': '標(biāo)題5-20個(gè)字符'}))
  # 使用自定義驗(yàn)證規(guī)則
  phone = fields.CharField(validators=[mobile_validate, ],
              error_messages={'required': '手機(jī)不能為空'},
              widget=widgets.TextInput(attrs={'class': "form-control",
                             'placeholder': u'手機(jī)號碼'}))
  email = fields.EmailField(required=False,
              error_messages={'required': u'郵箱不能為空','invalid': u'郵箱格式錯(cuò)誤'},
              widget=widgets.TextInput(attrs={'class': "form-control", 'placeholder': u'郵箱'}))

方式三:

 def clean(self):
     pwd = self.cleaned_data.get('pwd')
     r_pwd = self.cleaned_data.get('r_pwd')
     print(pwd, r_pwd)
     if pwd and r_pwd:
       if pwd == r_pwd:
         return self.cleaned_data
       raise ValidationError('兩次密碼不一致')
     else:
       return self.cleaned_data
   def clean_username(self):
     val = self.cleaned_data.get('username')
     user = UserInfo.objects.filter(name=val)
     if not user:
       return val
     else:
       raise ValidationError("用戶名已注冊")
   def clean_tel(self):
     val = self.cleaned_data.get('tel')
     if len(val) == 11:
       return val
     raise ValidationError('手機(jī)號格式錯(cuò)誤')

總結(jié):

'''
   局部鉤子:
     1、is_valid()
     2、self.errors
     3、self.full_clean()
     4、self._clean_fields() 校驗(yàn)每一個(gè)字段
    5、for 循環(huán)每一個(gè)字段名、驗(yàn)證規(guī)則對象
     6、
       驗(yàn)證通過:
         value = field.clean(value)
         self.cleaned_data[name] = value       添加到clean_data中
         利用反射、鉤子自定義驗(yàn)證規(guī)則
         hasattr(self, 'clean_%s' % name)      寫自定義方法
         value = getattr(self, 'clean_%s' % name)() 執(zhí)行自定義方法
           pass:
             self.cleaned_data[name] = value   添加到clean_data中
           no_pass:
             raise ValidationError(msg)     拋出異常
       不通過:
         raise ValidationError(msg)
   全局鉤子:
     1、is_valid()
     2、self.errors
     3、self.full_clean() 
     4、self._clean_form()  全部字段調(diào)用完成之后 調(diào)用
     5、self.clean() 重寫clean方法
     6、全局鉤子錯(cuò)誤:forms.errors.get("__all__")
   '''

總結(jié)

以上所述是小編給大家介紹的Django中的forms組件實(shí)例詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時(shí)回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!

相關(guān)文章

  • python實(shí)現(xiàn)得到一個(gè)給定類的虛函數(shù)

    python實(shí)現(xiàn)得到一個(gè)給定類的虛函數(shù)

    這篇文章主要介紹了python實(shí)現(xiàn)得到一個(gè)給定類的虛函數(shù)的方法,以wx的PyPanel類為例講述了打印以base_開頭的方法的實(shí)例,需要的朋友可以參考下
    2014-09-09
  • 使用 Python 查找本月的最后一天的方法匯總

    使用 Python 查找本月的最后一天的方法匯總

    這篇文章主要介紹了使用 Python 查找本月的最后一天,在本文中,我們學(xué)習(xí)了使用 datetime 和 calendar 等內(nèi)置庫以及 arrow 和 pandas 等第三方庫在 Python 中查找月份最后一天的各種方法,需要的朋友可以參考下
    2023-05-05
  • python的id()函數(shù)解密過程

    python的id()函數(shù)解密過程

    id()函數(shù)在使用過程中很頻繁,為此本人對此函數(shù)深入研究下,曬出代碼和大家分享下,希望對你們有所幫助
    2012-12-12
  • Python面向?qū)ο缶幊讨^承與多態(tài)詳解

    Python面向?qū)ο缶幊讨^承與多態(tài)詳解

    這篇文章主要介紹了Python面向?qū)ο缶幊讨^承與多態(tài),結(jié)合實(shí)例形式詳細(xì)分析了Python面向?qū)ο缶幊讨欣^承與多態(tài)的概念、使用方法及相關(guān)注意事項(xiàng),需要的朋友可以參考下
    2018-01-01
  • Python request post上傳文件常見要點(diǎn)

    Python request post上傳文件常見要點(diǎn)

    這篇文章主要介紹了Python request post上傳文件常見要點(diǎn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-11-11
  • 使用matlab 判斷兩個(gè)矩陣是否相等的實(shí)例

    使用matlab 判斷兩個(gè)矩陣是否相等的實(shí)例

    這篇文章主要介紹了使用matlab 判斷兩個(gè)矩陣是否相等的實(shí)例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-05-05
  • python庫geopandas讀取寫入空間數(shù)據(jù)及繪圖實(shí)例探索

    python庫geopandas讀取寫入空間數(shù)據(jù)及繪圖實(shí)例探索

    這篇文章主要為大家介紹了python庫geopandas讀取寫入空間數(shù)據(jù)及繪圖實(shí)例探索,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪<BR>
    2024-02-02
  • Python修改列表元素有哪些方法總結(jié)

    Python修改列表元素有哪些方法總結(jié)

    在Python中列表是一種可變序列,可以存儲任意類型的元素,而元組是一種不可變序列,也可以存儲各種類型的元素,下面這篇文章主要給大家介紹了關(guān)于Python修改列表元素有哪些方法的相關(guān)資料,需要的朋友可以參考下
    2023-05-05
  • Python3內(nèi)置json模塊編碼解碼方法詳解

    Python3內(nèi)置json模塊編碼解碼方法詳解

    Python3中我們利用內(nèi)置模塊json解碼和編碼JSON對象。json模塊提供了四個(gè)功能:dumps、dump、loads、load本文詳細(xì)講解了Python3內(nèi)置json模塊的詳細(xì)使用方法
    2021-10-10
  • Python中讀取和加解密PDF文件的詳細(xì)教程

    Python中讀取和加解密PDF文件的詳細(xì)教程

    在Python中讀取和加密PDF文件是一項(xiàng)常見且實(shí)用的任務(wù),尤其對于需要處理大量文檔自動(dòng)化處理的場景,本文將詳細(xì)介紹如何使用Python讀取PDF文件內(nèi)容以及如何使用不同的庫來給PDF文件加密,需要的朋友可以參考下
    2024-08-08

最新評論