django from組件 ,model—from,django的緩存機制,dango的信號,django的序列號

1.構建一個表單

假設你想在你的網站上建立一個簡單的表單,以得到用戶的名字。你須要相似這樣的模板:html

1
2
3
4
5
<form  action = "/your-name/"  method= "post" >
     <label  for = "your_name" >Your  name : </label>
     <input id= "your_name"  type= "text"  name = "your_name" >
     <input type= "submit"  value= "OK" >
</form>

這是一個很是簡單的表單。實際應用中,一個表單可能包含幾十上百個字段,其中大部分須要預填充,並且咱們預料到用戶未來回編輯-提交幾回才能完成操做。git

咱們可能須要在表單提交以前,在瀏覽器端做一些驗證。咱們可能想使用很是複雜的字段,以容許用戶作相似從日曆中挑選日期這樣的事情,等等。ajax

這個時候,讓Django 來爲咱們完成大部分工做是很容易的。正則表達式

so,兩個突出優勢:sql

    1 form表單提交時,數據出現錯誤,返回的頁面中仍能夠保留以前輸入的數據。數據庫

    2 方便地限制字段條件django

 

                                      2.在Django 中構建一個表單

                      Form 類瀏覽器

    咱們已經計劃好了咱們的 HTML 表單應該呈現的樣子。在Django 中,咱們的起始點是這裏:app

1
2
3
4
5
6
#forms.py
 
from django import forms
 
class NameForm(forms.Form):
    your_name = forms.CharField(label='Your name', max_length=100)

 它定義一個Form 類,只帶有一個字段(your_name)。ide

字段容許的最大長度經過max_length 定義。它完成兩件事情。首先,它在HTML 的<input> 上放置一個maxlength="100"(這樣瀏覽器將在第一時間阻止用戶輸入多於這個數目的字符)。它還意味着當Django 收到瀏覽器發送過來的表單時,它將驗證數據的長度。

Form 的實例具備一個is_valid() 方法,它爲全部的字段運行驗證的程序。當調用這個方法時,若是全部的字段都包含合法的數據,它將:

  • 返回True
  • 將表單的數據放到cleaned_data屬性中。

完整的表單,第一次渲染時,看上去將像:

1
2
<label for="your_name">Your name: </label>
<input id="your_name" type="text" name="your_name" maxlength="100">

 注意它不包含 <form> 標籤和提交按鈕。咱們必須本身在模板中提供它們。

                    視圖:

發送給Django 網站的表單數據經過一個視圖處理,通常和發佈這個表單的是同一個視圖。這容許咱們重用一些相同的邏輯。

當處理表單時,咱們須要在視圖中實例化它:

 

 

若是訪問視圖的是一個GET 請求,它將建立一個空的表單實例並將它放置到要渲染的模板的上下文中。這是咱們在第一個訪問該URL 時預期發生的狀況。

 

若是表單的提交使用POST 請求,那麼視圖將再次建立一個表單實例並使用請求中的數據填充它:form = NameForm(request.POST)。這叫作」綁定數據至表單「(它如今是一個綁定的表單)。

 

咱們調用表單的is_valid()方法;若是它不爲True,咱們將帶着這個表單返回到模板。這時表單再也不爲空(未綁定),因此HTML 表單將用以前提交的數據填充,而後能夠根據要求編輯並改正它。

 

 

若是is_valid()True,咱們將可以在cleaned_data 屬性中找到全部合法的表單數據。在發送HTTP 重定向給瀏覽器告訴它下一步的去向以前,咱們能夠用這個數據來更新數據庫或者作其它處理

 

 

            Django Form 類詳解:

                綁定的和未綁定的表單實例

 

綁定的和未綁定的表單 之間的區別很是重要:

  • 未綁定的表單沒有關聯的數據。當渲染給用戶時,它將爲空或包含默認的值。
  • 綁定的表單具備提交的數據,所以能夠用來檢驗數據是否合法。若是渲染一個不合法的綁定的表單,它將包含內聯的錯誤信息,告訴用戶如何糾正數據。
          •         字段詳解

          • 考慮一個比上面的迷你示例更有用的一個表單,咱們完成一個更加有用的註冊表單:

          • #forms.py from django import forms class RegisterForm(forms.Form): username = forms.CharField(max_length=100, error_messages={"min_length":"最短爲5個字符","required":"該字段不能爲空"}, ) password = forms.CharField(max_length=100, widget=widgets.PasswordInput(attrs={"placeholder":"password"}) ) telephone=forms.IntegerField( error_messages={ "invalid":"格式錯誤" } ) gender=forms.CharField( initial=2, widget=widgets.Select(choices=((1,'上海'),(2,'北京'),)) ) email = forms.EmailField() is_married = forms.BooleanField(required=False)
            orms.py
            
            from django import forms
            
            class RegisterForm(forms.Form):
                username = forms.CharField(max_length=100,
                                           error_messages={"min_length":"最短爲5個字符","required":"該字段不能爲空"},
                                           )
                password = forms.CharField(max_length=100,
                                           widget=widgets.PasswordInput(attrs={"placeholder":"password"})
                                            )
            
                telephone=forms.IntegerField(
                    error_messages={
                        "invalid":"格式錯誤"
                    }
            
                                            )
            
            
                gender=forms.CharField(
                      initial=2,
                      widget=widgets.Select(choices=((1,'上海'),(2,'北京'),))
                         )
            
                email = forms.EmailField()
                is_married = forms.BooleanField(required=False)
            複製代碼

            Widgets

            每一個表單字段都有一個對應的Widget 類,它對應一個HTML 表單Widget,例如<input type="text">

            在大部分狀況下,字段都具備一個合理的默認Widget。例如,默認狀況下,CharField 具備一個TextInput Widget,它在HTML 中生成一個<input type="text">

            字段的數據

            無論表單提交的是什麼數據,一旦經過調用is_valid() 成功驗證(is_valid() 返回True),驗證後的表單數據將位於form.cleaned_data 字典中。這些數據已經爲你轉換好爲Python 的類型。

            注:此時,你依然能夠從request.POST 中直接訪問到未驗證的數據,可是訪問驗證後的數據更好一些。

            在上面的聯繫表單示例中,is_married將是一個布爾值。相似地,IntegerField 和FloatField 字段分別將值轉換爲Python 的int 和float

            使用表單模板

            你須要作的就是將表單實例放進模板的上下文。若是你的表單在Context 中叫作form,那麼{{ form }}將正確地渲染它的<label> 和 <input>元素。

            表單渲染的選項

            對於<label>/<input> 對,還有幾個輸出選項:

            • {{ form.as_table }} 以表格的形式將它們渲染在<tr> 標籤中
            • {{ form.as_p }} 將它們渲染在<p> 標籤中
            • {{ form.as_ul }} 將它們渲染在<li> 標籤中

            注意,你必須本身提供<table> 或<ul> 元素。

            {{ form.as_p }}會渲染以下:

          • <form action="">
                <p>
                    <label for="id_username">Username:</label>
                    <input id="id_username" maxlength="100" name="username" type="text" required="">
                </p>
             
             
                <p>
                    <label for="id_password">Password:</label>
                    <input id="id_password" maxlength="100" name="password" placeholder="password" type="password" required="">
                </p>
             
             
                <p>
                    <label for="id_telephone">Telephone:</label> <input id="id_telephone" name="telephone" type="number" required="">
                </p>
             
             
                <p>
                    <label for="id_email">Email:</label> <input id="id_email" name="email" type="email" required="">
                </p>
             
             
                <p>
                    <label for="id_is_married">Is married:</label> <input id="id_is_married" name="is_married" type="checkbox">
                </p>
             
             
                <input type="submit" value="註冊">
            </form>
            View Code

             

          • 手工渲染字段:

            咱們沒有必要非要讓Django 來分拆表單的字段;若是咱們喜歡,咱們能夠手工來作(例如,這樣容許從新對字段排序)。每一個字段都是表單的一個屬性,可使用{{ form.name_of_field }} 訪問,並將在Django 模板中正確地渲染。例如:

            1
            2
            3
            4
            5
            < div  class="fieldWrapper">
                 {{ form.Username.errors }}
                 {{ form.Username.label_tag }}
                 {{ form.Username }}
            </ div >

            渲染表單的錯誤信息

            一、

            1
            2
            3
            registerForm=RegisterForm(request.POST)
            print(type(registerForm.errors))                      #< class  'django.forms.utils.ErrorDict'>
            print(type(registerForm.errors["username"]))          #< class  'django.forms.utils.ErrorList'>

            二、

            使用{{ form.name_of_field.errors }} 顯示錶單錯誤的一個清單,並渲染成一個ul。看上去可能像:

            1
            2
            3
            < ul  class="errorlist">
                 < li >Sender is required.</ li >
            </ ul >

             form組件的鉤子

            複製代碼
            def foo(request):
            
            
                if request.method=="POST":
            
                    regForm=RegForm(request.POST)
            
                    if regForm.is_valid():
                        pass
                        # 可用數據: regForm.cleaned_data,
                        # 將數據插入數據庫表中
            
            
                    else:
                        pass
                        # 可用數據: regForm.errors
                        # 能夠利用模板渲染講errors嵌套到頁面中返回
                        # 也能夠打包到一個字典中,用於ajax返回
            
                else:
                    regForm=RegForm()
                return render(request,"register.html",{"regForm":regForm})
            
                
            
                '''
                實例化時:
            
                    self.fields={
                        "username":"字段規則對象",
                        "password":"字段規則對象",
            
                    }
            
            
                is_valid時:
            
                    self._errors = {}
                    self.cleaned_data = {}
            
            
                    #局部鉤子:
            
                    for name, field in self.fields.items():
                          try:
            
                                value = field.clean(value)
                                self.cleaned_data[name] = value
                                if hasattr(self, 'clean_%s' % name):
                                    value = getattr(self, 'clean_%s' % name)()
                                    self.cleaned_data[name] = value
                          except ValidationError as e:
                                self.add_error(name, e)
            
                    # 全局鉤子:
            
                    self.clean()     # def self.clean():return self.cleaned_data
            
                    return  not self.errors    # True或者False
            

             

                                                                    form組件補充

一、Django內置字段以下:

  

複製代碼
Field
    required=True,               是否容許爲空
    widget=None,                 HTML插件
    label=None,                  用於生成Label標籤或顯示內容
    initial=None,                初始值
    help_text='',                幫助信息(在標籤旁邊顯示)
    error_messages=None,         錯誤信息 {'required': '不能爲空', 'invalid': '格式錯誤'}
    show_hidden_initial=False,   是否在當前插件後面再加一個隱藏的且具備默認值的插件(可用於檢驗兩次輸入是否一直)
    validators=[],               自定義驗證規則
    localize=False,              是否支持本地化
    disabled=False,              是否能夠編輯
    label_suffix=None            Label內容後綴
 
 
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,         小數位長度
 
BaseTemporalField(Field)
    input_formats=None          時間格式化   
 
DateField(BaseTemporalField)    格式:2015-09-01
TimeField(BaseTemporalField)    格式:11:12
DateTimeField(BaseTemporalField)格式:2015-09-01 11:12
 
DurationField(Field)            時間間隔:%d %H:%M:%S.%f
    ...
 
RegexField(CharField)
    regex,                      自定製正則表達式
    max_length=None,            最大長度
    min_length=None,            最小長度
    error_message=None,         忽略,錯誤信息使用 error_messages={'invalid': '...'}
 
EmailField(CharField)      
    ...
 
FileField(Field)
    allow_empty_file=False     是否容許空文件
 
ImageField(FileField)      
    ...
    注:須要PIL模塊,pip3 install Pillow
    以上兩個字典使用時,須要注意兩點:
        - form表單中 enctype="multipart/form-data"
        - view函數中 obj = MyForm(request.POST, request.FILES)
 
URLField(Field)
    ...
 
 
BooleanField(Field)  
    ...
 
NullBooleanField(BooleanField)
    ...
 
ChoiceField(Field)
    ...
    choices=(),                選項,如:choices = ((0,'上海'),(1,'北京'),)
    required=True,             是否必填
    widget=None,               插件,默認select插件
    label=None,                Label內容
    initial=None,              初始值
    help_text='',              幫助提示
 
 
ModelChoiceField(ChoiceField)
    ...                        django.forms.models.ModelChoiceField
    queryset,                  # 查詢數據庫中的數據
    empty_label="---------",   # 默認空顯示內容
    to_field_name=None,        # HTML中value的值對應的字段
    limit_choices_to=None      # ModelForm中對queryset二次篩選
     
ModelMultipleChoiceField(ModelChoiceField)
    ...                        django.forms.models.ModelMultipleChoiceField
 
 
     
TypedChoiceField(ChoiceField)
    coerce = lambda val: val   對選中的值進行一次轉換
    empty_value= ''            空值的默認值
 
MultipleChoiceField(ChoiceField)
    ...
 
TypedMultipleChoiceField(MultipleChoiceField)
    coerce = lambda val: val   對選中的每個值進行一次轉換
    empty_value= ''            空值的默認值
 
ComboField(Field)
    fields=()                  使用多個驗證,以下:即驗證最大長度20,又驗證郵箱格式
                               fields.ComboField(fields=[fields.CharField(max_length=20), fields.EmailField(),])
 
MultiValueField(Field)
    PS: 抽象類,子類中能夠實現聚合多個字典去匹配一個值,要配合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)     文件選項,目錄下文件顯示在頁面中
    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時候,可解析爲192.0.2.1, PS:protocol必須爲both才能啓用
 
SlugField(CharField)           數字,字母,下劃線,減號(連字符)
    ...
 
UUIDField(CharField)           uuid類型
    ...
View Code

 

二、Django內置插件:

 

TextInput(Input)
NumberInput(TextInput)
EmailInput(TextInput)
URLInput(TextInput)
PasswordInput(TextInput)
HiddenInput(TextInput)
Textarea(Widget)
DateInput(DateTimeBaseInput)
DateTimeInput(DateTimeBaseInput)
TimeInput(DateTimeBaseInput)
CheckboxInput
Select
NullBooleanSelect
SelectMultiple
RadioSelect
CheckboxSelectMultiple
FileInput
ClearableFileInput
MultipleHiddenInput
SplitDateTimeWidget
SplitHiddenDateTimeWidget
SelectDateWidget
複製代碼
View Code

 


三、經常使用選擇插件:

 

# 單radio,值爲字符串
# user = fields.CharField(
#     initial=2,
#     widget=widgets.RadioSelect(choices=((1,'上海'),(2,'北京'),))
# )
 
# 單radio,值爲字符串
# user = fields.ChoiceField(
#     choices=((1, '上海'), (2, '北京'),),
#     initial=2,
#     widget=widgets.RadioSelect
# )
 
# 單select,值爲字符串
# user = fields.CharField(
#     initial=2,
#     widget=widgets.Select(choices=((1,'上海'),(2,'北京'),))
# )
 
# 單select,值爲字符串
# user = fields.ChoiceField(
#     choices=((1, '上海'), (2, '北京'),),
#     initial=2,
#     widget=widgets.Select
# )
 
# 多選select,值爲列表
# user = fields.MultipleChoiceField(
#     choices=((1,'上海'),(2,'北京'),),
#     initial=[1,],
#     widget=widgets.SelectMultiple
# )
 
 
# 單checkbox
# user = fields.CharField(
#     widget=widgets.CheckboxInput()
# )
 
 
# 多選checkbox,值爲列表
# user = fields.MultipleChoiceField(
#     initial=[2, ],
#     choices=((1, '上海'), (2, '北京'),),
#     widget=widgets.CheckboxSelectMultiple
# )
View Code
相關文章
相關標籤/搜索