django-forms組件

08.19自我總結

django-forms組件

一.forms的做用

  • 前端和後端都要校驗
  • 前端校驗的目的:減小後臺代碼鏈接數據庫的壓力

用forms能夠同時完成前端和後端同時校驗且減小代碼量html

二.forms的基本使用:

1.定義數據的時候導入from類

2.字段經過fields進行導入

3.演示

views.py前端

from django.forms import Form
from django.forms import fields
class LoginForm(Form):
    ### 所有都是驗證的規則
    username = fields.CharField(
        required=True,  ### 不能爲空
        max_length=18,  ### 最大的長度是18
        min_length=6,   ### 最小的長度是6
        error_messages = {  ### 對英文進行重寫
            "required" : "不能爲空",
            "max_length":"太長了",
            "min_length":"過短了",
        }
    )

    pwd = fields.CharField()

4.方法中對於傳參進行定義

views.pypython

def login(request):
    if request.method == 'GET':
        return render(request, "login.html")
    else:
        # username = request.POST.get('username')
        # pwd = request.POST.get('pwd')
        obj = LoginForm(request.POST) ## {"username":'xx', 'pwd':'xx'}
        if obj.is_valid():
            print(obj.cleaned_data) ## 對象
            else:
                print(obj.errors) ### 對象 __str__

                return render(request, "login.html", {'obj':obj})

5.html中對於返回值進行渲染

login.htmlgit

渲染方式一:正則表達式

<form action="/login/" method="post">
    username: <input type="text" name="username">{{ obj.errors.username.0 }}<br>
    password: <input type="password" name="pwd">{{ obj.errors.pwd.0 }}<br>
    <input type="submit" value="提交"><br>
</form>

渲染方式二:數據庫

#前提標題由forms組件進行
{{obj.username}} #對於字段的input框
{{obj.as_p }}#對象的全部字段
{{obj.errors.username }}#對象的錯誤信息

三.forms組件全部參數

1.Field

required=True,               是否容許爲空
widget=None,                 HTML插件
label=None,                  用於生成Label標籤或顯示內容
initial=None,                初始值
help_text='',                幫助信息(在標籤旁邊顯示)
error_messages=None,         錯誤信息 {'required': '不能爲空', 'invalid': '格式錯誤'}
validators=[],               自定義驗證規則
localize=False,              是否支持本地化
disabled=False,              是否能夠編輯
label_suffix=None            Label內容後綴

2.CharField(Field)

max_length=None,             最大長度
min_length=None,             最小長度
strip=True                   是否移除用戶輸入空白

3.IntegerField(Field)

max_value=None,              最大值
min_value=None,              最小值

4.FloatField(IntegerField)

max_value=None,              最大值
min_value=None,              最小值

5.DecimalField(IntegerField)

max_value=None,              最大值
min_value=None,              最小值
max_digits=None,             總長度
decimal_places=None,         小數位長度

6.BaseTemporalField(Field)

input_formats=None          時間格式化

7.DateField(BaseTemporalField)

格式:2015-09-01

8.TimeField(BaseTemporalField)

格式:11:12

9.DateTimeField(BaseTemporalField)

格式:2015-09-01 11:12

10.DurationField(Field)

時間間隔:%d %H:%M:%S.%f

11.RegexField(CharField)

regex,                      自定製正則表達式
max_length=None,            最大長度
min_length=None,            最小長度
error_message=None,         忽略,錯誤信息使用 error_messages={'invalid': '...'}

12.EmailField(CharField)

13.FileField(Field)

allow_empty_file=False     是否容許空文件

14.ImageField(FileField)

注:須要PIL模塊,pip3 install Pillow
    以上兩個字典使用時,須要注意兩點:
        - form表單中 enctype="multipart/form-data"
        - view函數中 obj = MyForm(request.POST, request.FILES)

15.URLField(Field)

16.BooleanField(Field)

17.NullBooleanField(BooleanField)

18.ChoiceField(Field)

choices=(),                選項,如:choices = ((0,'上海'),(1,'北京'),)
required=True,             是否必填
widget=None,               插件,默認select插件
label=None,                Label內容
initial=None,              初始值
help_text='',              幫助提示

19.ModelChoiceField(ChoiceField)

...                        django.forms.models.ModelChoiceField
    queryset,                  # 查詢數據庫中的數據
    empty_label="---------",   # 默認空顯示內容
    to_field_name=None,        # HTML中value的值對應的字段
    limit_choices_to=None      # ModelForm中對queryset二次篩選

20.ModelMultipleChoiceField(ModelChoiceField)

...                        django.forms.models.ModelMultipleChoiceField

21.TypedChoiceField(ChoiceField)

coerce = lambda val: val   對選中的值進行一次轉換
empty_value= ''            空值的默認值

22.MultipleChoiceField(ChoiceField)

23.TypedMultipleChoiceField(MultipleChoiceField)

coerce = lambda val: val   對選中的每個值進行一次轉換
empty_value= ''            空值的默認值

24.ComboField(Field)

fields=()                  使用多個驗證,以下:即驗證最大長度20,又驗證郵箱格式
                               fields.ComboField(fields=[fields.CharField(max_length=20), fields.EmailField(),])

25.MultiValueField(Field)

PS: 抽象類,子類中能夠實現聚合多個字典去匹配一個值,要配合MultiWidget使用

26.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']

27.FilePathField(ChoiceField) 文件選項,目錄下文件顯示在頁面中

path,                      文件夾路徑
match=None,                正則匹配
recursive=False,           遞歸下面的文件夾
allow_files=True,          容許文件
allow_folders=False,       容許文件夾
required=True,
widget=None,
label=None,
initial=None,
help_text=''

28.GenericIPAddressField

protocol='both',           both,ipv4,ipv6支持的IP格式
unpack_ipv4=False          解析ipv4地址,若是是::ffff:192.0.2.1時候,可解析爲192.0.2.1, PS:protocol必須爲both才能啓用

29.SlugField(CharField)

數字,字母,下劃線,減號(連字符)django

30.UUIDField(CharField)

uuid類型後端

四.相關參數使用演示

from django.forms import Form
from django.forms import fields
from django.forms import Widget,PasswordInput
class LoginForm(Form):
    username = fields.CharField(
        required=True,
        # label='用戶名',
        # initial=666,
        # help_text='幫助信息',
        # # disabled=True,
        # label_suffix='--->',
        max_length=18,
        min_length=6,
        error_messages={
            'required' : '用戶名不能爲空',
            'max_length': '用戶名不能超過18',
            'min_length': '用戶名最小爲6',
        }
    )
    # password = fields.IntegerField(
    #     required=True,
    #     max_value=99999999,
    #     min_value=100000,
    #     error_messages={
    #         'required' : '密碼不能爲空',
    #         'invalid'  :  '格式不正確',
    #         'min_value': '密碼最少六位',
    #         'max_value': '密碼最多12位',
    #     },
    #     # widget=PasswordInput
    # )
    email = fields.EmailField()
def login(request):
    if request.method == 'GET':
        obj = LoginForm()
        print(obj)
        return render(request, 'login.html', {'obj':obj})
    else:
        # username = request.POST.get('username')
        # print(username)
        obj = LoginForm(request.POST)
        if obj.is_valid():
            print(obj.cleaned_data)
        else:
            errors = obj.errors
            # <ul class="errorlist">
            #   <li>username
            #       <ul class="errorlist">
            #           <li>This field is required.</li>
            #       </ul>
            #   </li>
            # </ul>
            # print(type(errors))
            # print(errors)
        return render(request, 'login.html', {'obj' : obj})
相關文章
相關標籤/搜索