1. 程式人生 > >Form驗證隨筆 | Django

Form驗證隨筆 | Django

方法 創建表 utf-8 空白 attrs forms pla blank add

from django.shortcuts import render
from app01.dadforms import DetailForm, VerifyForm


def index(request):
    # 創建表單對象
    detail_form = DetailForm(request.POST)
    # 驗證輸入表單數據
    detail_form.is_valid()
    # 打印輸入的正確數據
    print(detail_form.clean())
    return render(request, index.html, locals())


def field_verified(request): if request.method == GET: # 創建表單對象 verify_form = VerifyForm() return render(request, verify.html, locals()) elif request.method == POST: print(我是post方法) # 創建表單對象 verify_form = VerifyForm(request.POST, request.FILES)
# 驗證字段 verify_form.is_valid() # 打印正確字段 print(verify_form.clean()) print(verify_form.errors.as_json()) # errors = verify_form.errors return render(request, verify.html, locals())
from django import forms
from django.forms import fields
# 導入插件模塊,以自定義input標簽
from
django.forms import widgets class DetailForm(forms.Form): """1.forms中的__init__方法引入了fields等模塊的內容, 所以,可以這麽寫:forms.CharField()""" # 用戶名驗證 user = fields.CharField( # widget=widgets.PasswordInput widget=widgets.TextInput(attrs={ class:c1, id:p, # 默認顯示值 placeholder:用戶名 }) # 2.TextInput()文本輸入框有一個attr方法,可以給input框添加屬性; ) # 3.選項框 # sex = fields.ChoiceField( # choices=[ # (1, ‘男‘), # (2, ‘女‘) # ] # ) # 4.通過CharField()重現選項框,通過字段指定插件 sex = fields.CharField( widget = widgets.Select( choices=[ (1, ), (2, ) ] ) ) # 表單的作用:1.驗證;2.生成html標簽;3.數據轉換; # 內部會對字符串做一個類型轉換,轉換成數字; score = fields.IntegerField() addr = fields.CharField( widget = widgets.RadioSelect( choices=[ (1, 上海), (2, 溫州) ] ) ) # ---------------------------- 字段驗證 from django.core.validators import RegexValidator class VerifyForm(forms.Form): """ required=True, widget=None, label=None, initial=None, help_text=‘‘, error_messages=None, show_hidden_initial=False, validators=[], localize=False, label_suffix=None(label後綴符) """ # CharField()中__init__下有長度,以及是否取出空白的參數;(strip=True) # 而且繼承Field()中的所有初始字段; user_name = fields.CharField( max_length=6, min_length=6, # 1.默認必填,False表示可以為空; required=True, # 2.設置默認值 initial=大山的姑娘, # 3.自定義驗證規則 validators=[RegexValidator(r159[0-9]+$, aaaaaaa, code=d1), RegexValidator(r^[0-9]+$, bbbbbbb, code=d2)], # 4.錯誤信息,error_messages優先級比自定義規則的驗證錯誤信息要高,會覆蓋上面的; # 如果自定義驗證有多個規則,可以通過RegexValidator裏的第3個參數code指定顯示驗證信息; # 錯誤信息裏,默認兩個參數required和invalid(必須,格式); # 還有max_length等,前面加什麽參數,code就是什麽; error_messages={required: 不能為空, d1: 1111111, d2:22222222, max_length: too long}, # label,HTML中需要添加{{表單對象.label}} label=名字, label_suffix=::::, widget=widgets.TextInput(attrs={ class: a1, placeholder: 山炮 }), # 是否可以編輯 disabled=True ) # 5.數字,有數值的限制; user_score = fields.IntegerField( max_value=20, required=True, initial=1, error_messages={required: not blank, max_value: num too big} ) # 6.DecimalField繼承IntegerField user_tax = fields.DecimalField( max_digits=4, # 總長度 decimal_places=2, # 小數位長度 # error_messages={‘invalid‘: ‘geshicuowu‘} ) # 7.正則表達式input框 user_tel = fields.RegexField( max_length=6, regex=(r159[0-9]+$), error_messages={invalid: not true, max_length:tooLong}, # [{"message": "not true", "code": "invalid"}] code表示錯誤類型 ), # 8.文件上傳 # 註意兩點: # 1.form表單中加入enctype="multipart/form-data" # 2.視圖函數中創建表單對象時,obj = Myform(request.POST, request.FILES) user_file = fields.FileField( allow_empty_file=False, ), # 圖片上傳,ImageField繼承FileField user_pic = fields.ImageField( allow_empty_file=False, ) # 9.ChoiceField選擇框,默認是Select框; # TypedChoiceField() user_course = fields.TypedChoiceField( # 類型轉化的匿名函數 coerce = lambda x: int(x), choices=[ (1, 語文), (2, 數學), (3, 未填寫) ], initial=3, ) # 10.多選框MultipleChoiceField() user_class = fields.MultipleChoiceField( choices=[ (1, 09-03), (2, 09-02), (3, 09-01) ], initial=[2, 3], ) # 11.組合的字段驗證 user_join = fields.ComboField( fields=[ fields.CharField(max_length=6), fields.EmailField(), ] ) # 12.多個框組合,0577-66666 user_local_phone = fields.SplitDateTimeField()
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="verify.html" method="POST" enctype="multipart/form-data">
        {% csrf_token %}
        {{ verify_form.user_name }}<br>
        {{ verify_form.user_score }}<br>
        {{ verify_form.user_tax }}<br>
        {{ verify_form.user_tel }}<br>
        {{ verify_form.user_file }}<br>
        {{ verify_form.user_pic }}<br>
        {{ verify_form.user_course }}<br>
        {{ verify_form.user_class }}<br>
        {{ verify_form.user_join }}<br>
        {{ verify_form.user_local_phone }}<br>

        <input type="submit", value="提交">
    </form>
</body>
</html>

Form驗證隨筆 | Django