Django的Form主要具備一下幾大功能:html
一.建立Form類前端
#!/usr/bin/env python from django.forms import Form from django.forms import widgets from django.forms import fields class MyForm(Form): user = fields.CharField( widget=widgets.TextInput(attrs={"id": "i1", "class": "c1"}), # 定製html標籤 label="用戶名" ) gender = fields.ChoiceField( choices=((1, "男"), (2, "女")), initial=2, # 設置默認值 widget=widgets.RadioSelect, label="性別" ) city = fields.CharField( initial=2, widget=widgets.Select(choices=((1,"上海"), (2,"北京"), (3,"重慶"))), label="城市" ) pwd = fields.CharField( widget=widgets.PasswordInput(attrs={"class":"p1"}, render_value=True), label="性別" )
2.view函數處理python
from django.shortcuts import render, redirect # Create your views here. from day60app.form_cls import MyForm def index(request): if request.method == "GET": obj = MyForm() return render(request, "index.html", {"obj": obj}) elif request.method == "POST": obj = MyForm(request.POST, request.FILES) if obj.is_valid(): v = obj.cleaned_data print("用戶驗證成功信息", v) return redirect("http://www.jd.com") else: v = obj.errors print("錯誤信息", v) return render(request, "index.html", {"obj": obj})
3. 生成html標籤mysql
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>Hello World</h1> <form action="/index/" method="post" enctype="multipart/form-data" novalidate> <p>{{ obj.user.label }}{{ obj.user }}{{ obj.user.errors.0 }}</p> <p>{{ obj.gender.label }}{{ obj.gender }}{{ obj.gender.errors.0 }}</p> <p>{{ obj.pwd.label }}{{ obj.pwd }}{{ obj.pwd.errors.0 }}</p> <p>{{ obj.city.label }}{{ obj.city }}{{ obj.city.errors.0 }}</p> <input type="submit" value="提交"> </form> </body>
建立Form類時,主要涉及到 【字段】 和 【插件】,字段用於對用戶請求數據的驗證,插件用於自動生成HTML;git
一、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內容後綴
示例:sql
class TestForm(forms.Form): user = fields.CharField( required=True, max_length=12, min_length=3, error_messages={}, widget = widgets.TextInput(attrs={"class":123}), # 定製html插件,屬性:用attrs參數 # widget= widgets.Textarea() label="姓名", initial='laiying', show_hidden_initial=False, # validators=[] #自定製驗證規則 # disabled=True label_suffix=":" )
Django內置字段以下:數據庫
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類型
實例一: 在頁面上不用加self直接顯示input框django
效果:json
代碼以下:
<body>
{{txt}}
</body>
def test(request): if request.methon == 'GET': txt = "<input type='text' />" from django.utils.safestring import mark_safe txt = mark_safe(txt) return render(request,'text.html',{'txt':txt})
注:UUID是根據MAC以及當前時間等建立的不重複的隨機字符串
>>> import uuid # make a UUID based on the host ID and current time >>> uuid.uuid1() # doctest: +SKIP UUID('a8098c1a-f86e-11da-bd1a-00112444be1e') # make a UUID using an MD5 hash of a namespace UUID and a name >>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org') UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e') # make a random UUID >>> uuid.uuid4() # doctest: +SKIP UUID('16fd2706-8baf-433b-82eb-8c7fada847da') # make a UUID using a SHA-1 hash of a namespace UUID and a name >>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org') UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d') # make a UUID from a string of hex digits (braces and hyphens ignored) >>> x = uuid.UUID('{00010203-0405-0607-0809-0a0b0c0d0e0f}') # convert a UUID to a string of hex digits in standard form >>> str(x) '00010203-0405-0607-0809-0a0b0c0d0e0f' # get the raw 16 bytes of the UUID >>> x.bytes b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f' # make a UUID from a 16-byte string >>> uuid.UUID(bytes=x.bytes) UUID('00010203-0405-0607-0809-0a0b0c0d0e0f')
二、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
經常使用選擇插件
<strong># 單radio,值爲字符串</strong> # user = fields.CharField( # initial=2, # widget=widgets.RadioSelect(choices=((1,'上海'),(2,'北京'),)) # ) <strong># 單radio,值爲字符串</strong> # user = fields.ChoiceField( # choices=((1, '上海'), (2, '北京'),), # initial=2, # widget=widgets.RadioSelect # ) <strong># 單select,值爲字符串</strong> # user = fields.CharField( # initial=2, # widget=widgets.Select(choices=((1,'上海'),(2,'北京'),)) # ) <strong># 單select,值爲字符串</strong> # user = fields.ChoiceField( # choices=((1, '上海'), (2, '北京'),), # initial=2, # widget=widgets.Select # ) <strong># 多選select,值爲列表</strong> # user = fields.MultipleChoiceField( # choices=((1,'上海'),(2,'北京'),), # initial=[1,], # widget=widgets.SelectMultiple # ) <strong># 單checkbox</strong> # user = fields.CharField( # widget=widgets.CheckboxInput() # ) <strong># 多選checkbox,值爲列表</strong> # user = fields.MultipleChoiceField( # initial=[2, ], # choices=((1, '上海'), (2, '北京'),), # widget=widgets.CheckboxSelectMultiple # )
示例:
#select框的兩種寫法 #方法一: # xdb = fields.CharField( # widget=widgets.Select(choices=[(1,'剛娘'),(2,'鐵娘'),(3,'鋼彈')]) # ) #方法二: # xdb = fields.IntegerField( # widget=widgets.Select(choices=[(1,'剛娘'),(2,'鐵娘'),(3,'鋼彈')]) # ) # xdb = fields.ChoiceField( # choices=[(1,'剛娘'),(2,'鐵娘'),(3,'鋼彈')] # ) #多選下拉框(有自定義屬性) # xdb = fields.MultipleChoiceField( # choices=[(1, '剛娘'), (2, '鐵娘'), (3, '鋼彈')], # widget=widgets.SelectMultiple(attrs={'class':'c1'}) #後面參數是定製屬性 # ) #單選checkbox # xdb = fields.CharField( # widget=widgets.CheckboxInput() # ) #多選checkbox (多個checkbox,二選一) # xdb = fields.MultipleChoiceField( # initial=[2, ], # choices=((1, '上海'), (2, '北京'),), # widget=widgets.CheckboxSelectMultiple # ) #多個選項Radio (互斥 三選一) # xdb = fields.ChoiceField( # choices=((1, '上海'), (2, '北京'),(3, '北京1'),), # initial=2, # widget=widgets.RadioSelect # )
在使用選擇標籤時,須要注意Choices 的選項能夠從數據庫中獲取,可是因爲是靜態字段***獲取的值沒法實時更新***,那麼須要自定義構造方法從而達到此目的。
方法一:(推薦使用)
from django.db import models class UserInfo(models.Model): username = models.CharField(max_length=32) email = models.EmailField(max_length=32)
from django.conf.urls import url from django.contrib import admin from app02 import views as v2 urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^love/', v2.love), ]
from app01 import models class LoveForm(forms.Form): price = fields.IntegerField() user_id = fields.IntegerField( # widget=widgets.Select(choices=[(0,'alex'),(1,'劉皓宸'),(2,'楊建'),]) widget=widgets.Select() ) #自定義構造方法,實時刷新頁面數據 def __init__(self, *args, **kwargs): super(LoveForm, self).__init__(*args, **kwargs) self.fields['user_id'].widget.choices = models.UserInfo.objects.values_list('id', 'username')
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>有緣千里來相會</h1> <p>價格:{{ obj.price }}</p> <p>姑娘:{{ obj.user_id }}</p> </body> </html>
方法二:(不推薦使用)
使用django提供的ModelChoiceField和ModelMultipChoiceField字段來實現
(這種django內置的方法不推薦使用,若是要在前端顯示數據庫中的用戶名,須要依賴models中的__str__方法,並且一個class中只有一個__str__, 若是在有的場景中須要同時顯示如id user, age等多個字段名時,這個方法就作不到)
from django.conf.urls import url from django.contrib import admin from app02 import views as v2 urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^love/', v2.love), ]
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>有緣千里來相會</h1> <p>價格:{{ obj.price }}</p> <p>姑娘:{{ obj.user_id2 }}</p> </body> </html>
from django.forms.models import ModelChoiceField class LoveForm(forms.Form): price = fields.IntegerField() user_id2 = ModelChoiceField( queryset=models.UserInfo.objects.all(), to_field_name='id' )
from django.db import models class UserInfo(models.Model): username = models.CharField(max_length=32) email = models.EmailField(max_length=32) def __str__(self): return self.username # 注意:依賴models中的str方法
1.Form組件的驗證
前端:form表單
後臺:建立form類,當請求到來時,先匹配,匹配出正確和錯誤信息。
Django的Form驗證實例:
建立project,進行基礎配置文件配置
STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR,"static"), )
MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', # 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ]
import pymysql pymysql.install_as_MySQLdb()
from django.conf.urls import url from django.contrib import admin from app01.views import account urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^form1/', account.form1), # url(r'^test/', account.test), ]
from django.shortcuts import render,HttpResponse from app01.forms import Form1 def form1(request): if request.method=="POST": #這裏POST必定要大寫 #一般獲取請求信息 #request.POST.get("user",None) #request.POST.get("pwd",None) #獲取請求內容,作驗證 f = Form1(request.POST) #request.POST:將接收到的數據經過Form1驗證 if f.is_valid(): #驗證請求的內容和Form1裏面的是否驗證經過。經過是True,不然False。 print(f.cleaned_data) #cleaned_data類型是字典,裏面是提交成功後的信息 else: #錯誤信息包含是否爲空,或者符合正則表達式的規則 print(type(f.errors),f.errors) #errors類型是ErrorDict,裏面是ul,li標籤 return render(request,"account/form1.html",{"error":f.errors}) return render(request,"account/form1.html")
<body> {#{{ error }}接收後臺返回的錯誤信息封裝在ul,li標籤裏面:#} {{ error }} <form action="/form1/" method="POST"> <div> <input type="text" name="user" /> </div> <div> <input type="text" name="pwd" /> </div> <div> <input type="submit" value="提交" /> </div> </form> </body>
from django import forms class Form1(forms.Form): user = forms.CharField() pwd = forms.CharField()
訪問頁面:
沒有輸入內容後提交,經過模板語言展現了錯誤信息
Django強大之form驗證時不用自定義錯誤信息就能夠返回錯誤信息到前端以標籤方式展示。
.is_valid():返回True或者False .cleaned_data:經過驗證後的數據 errors: .error.get("user",None)error封裝全部的錯誤信息,若是沒有獲取到,默認爲None。 .error.get["pwd"]直接獲取到ul、li。
如:
from django import forms class Form1(forms.Form): user = forms.CharField() pwd = forms.CharField()
<form action="/form1/" method="POST"> <div class="input-group"> {#接收後臺傳過來的form對象,自動生成input標籤#} {{ form.user }} {#從後臺傳過來的error是字典,直接{{ error.user.0 }}呈現錯誤信息#} {#若是後臺返回了錯誤信息,將錯誤信息放入span標籤,在頁面顯示,不然不顯示#} {% if error.user.0 %} <span>{{ error.user.0 }}</span> {% endif %} </div> <div class="input-group"> {{ form.pwd }} {% if error.pwd.0 %} <span>{{ error.pwd.0 }}</span> {% endif %} </div> <div> <input type="submit" value="提交" /> </div> </form>
def form1(request): if request.method == "POST": f = Form1(request.POST) if f.is_valid(): print(f.cleaned_data) else: return render(request,"account/form1.html",{"error":f.errors,"form":f}) else: # 若是不是post提交數據,就不傳參數建立對象,並將對象返回給前臺,直接生成input標籤,內容爲空 f = Form1() return render(request,"account/form1.html",{"form":f}) return render(request,"account/form1.html")
注:
頁面展現:
注:這裏的input標籤是後端返回form對象到前端經過{{ form.xxx }}所建立的
更強大的功能:
forms裏面的字段:
required:是否能夠爲空。required=True 不能夠爲空,required=False 能夠爲空 max_length=4 最多4個值,超過不會顯示 min_length=2 至少兩個值,少於兩個會返回提示信息 error_messages={'required': '郵箱不能爲空', 'invalid': '郵箱格式錯誤'} 自定義錯誤信息,invalid 是格式錯誤 widget=forms.TextInput(attrs={'class': 'c1'}) 給自動生成的input標籤自定義class屬性 widget=forms.Textarea() 生成Textarea標籤。widget默認生成input標籤
實例:
from django.db import models # Create your models here. class Author(models.Model): """ 做者 """ name = models.CharField(max_length=100) age = models.IntegerField() class BookType(models.Model): """ 圖書類型 """ caption = models.CharField(max_length=64) class Book(models.Model): """ 圖書 """ name = models.CharField(max_length=64) pages = models.IntegerField() price = models.DecimalField(max_digits=10,decimal_places=2) pubdate = models.DateField() authors = models.ManyToManyField(Author) book_type = models.ForeignKey(BookType)
from django import forms from app01 import models class Form1(forms.Form): user = forms.CharField( widget=forms.TextInput(attrs={'class': 'c1'}), error_messages={'required': '用戶名不能爲空'}, ) pwd = forms.CharField(max_length=4, min_length=2,required=True) email = forms.EmailField(error_messages={'required': '郵箱不能爲空', 'invalid': '郵箱格式錯誤'}) memo = forms.CharField( widget=forms.Textarea() ) #直接寫數據 # user_type_choice = ( # (0, '普通用戶'), # (1, '高級用戶'), # ) #經過BookType表查詢信息,values_list拿到的是元組。id做爲value顯示,caption做爲text在頁面顯示 # user_type_choice = models.BookType.objects.values_list('id', 'caption') # book_type = forms.CharField( # widget=forms.widgets.Select(choices=user_type_choice, attrs={'class': "form-control"})) #寫上如下代碼就不用擔憂數據庫添加了數據而不能及時獲取了 def __init__(self, *args, **kwargs): #每次建立Form1對象時執行init方法 super(Form1, self).__init__(*args, **kwargs) self.fields['book_type'] = forms.CharField( widget=forms.widgets.Select(choices=models.BookType.objects.values_list('id', 'caption'), attrs={'class': "form-control"}))
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .input-group{ position: relative; padding: 20px; width: 250px; } .input-group input{ width: 200px; display: inline-block; } .inline-group span{ display: inline-block; position: absolute; height: 12px; font-size: 8px; border: 1px solid red; background-color: coral; color: white; top: 41px; left: 20px; width: 202px; } </style> </head> <body> <form action="/form1/" method="POST"> <div class="input-group"> {# 接收後臺傳過來的form對象,自動生成input標籤#} {{ form.user }} {# 從後臺傳過來的error是字典,直接{{ error.user.0 }}呈現錯誤信息#} {# 若是後臺返回了錯誤信息,將錯誤信息放入span標籤,在頁面顯示,不然不顯示#} {% if error.user.0 %} <span>{{ error.user.0 }}</span> {% endif %} </div> <div class="input-group"> {{ form.pwd }} {% if error.pwd.0 %} <span>{{ error.pwd.0 }}</span> {% endif %} </div> <div class="input-group"> {{ form.email }} {% if error.email.0 %} <span>{{ error.email.0 }}</span> {% endif %} </div> <div class="input-group"> {{ form.memo }} {% if error.memo.0 %} <span>{{ error.memo.0 }}</span> {% endif %} </div> <div class="input-group"> {{ form.book_type }} {% if error.book_type.0 %} <span>{{ error.book_type.0 }}</span> {% endif %} </div> <div> <input type="submit" value="提交" /> </div> </form> </body> </html>
from django.shortcuts import render,HttpResponse from app01.forms import Form1 from app01.models import * # def test(req): # BookType.objects.create(caption='技術') # BookType.objects.create(caption='文學') # BookType.objects.create(caption='動漫') # BookType.objects.create(caption='男人裝') # return HttpResponse("ok") def form1(request): if request.method == "POST": f = Form1(request.POST) if f.is_valid(): print(f.cleaned_data) else: return render(request,"account/form1.html",{"error":f.errors,"form":f}) else: # 若是不是post提交數據,就不傳參數建立對象,並將對象返回給前臺,直接生成input標籤,內容爲空 f = Form1() return render(request,"account/form1.html",{"form":f}) return render(request,"account/form1.html")
Django裏面沒有手機驗證,沒有的須要自定義
示例:
Form:
#!/usr/bin/env python # -*- coding:utf-8 -*- import re from django import forms from django.core.exceptions import ValidationError 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('手機號碼格式錯誤') class PublishForm(forms.Form): user_type_choice = ( (0, u'普通用戶'), (1, u'高級用戶'), ) user_type = forms.IntegerField(widget=forms.widgets.Select(choices=user_type_choice, attrs={'class': "form-control"})) title = forms.CharField(max_length=20, min_length=5, error_messages={'required': u'標題不能爲空', 'min_length': u'標題最少爲5個字符', 'max_length': u'標題最多爲20個字符'}, widget=forms.TextInput(attrs={'class': "form-control", 'placeholder': u'標題5-20個字符'})) memo = forms.CharField(required=False, max_length=256, widget=forms.widgets.Textarea(attrs={'class': "form-control no-radius", 'placeholder': u'詳細描述', 'rows': 3})) phone = forms.CharField(validators=[mobile_validate, ], error_messages={'required': u'手機不能爲空'}, widget=forms.TextInput(attrs={'class': "form-control", 'placeholder': u'手機號碼'})) email = forms.EmailField(required=False, error_messages={'required': u'郵箱不能爲空','invalid': u'郵箱格式錯誤'}, widget=forms.TextInput(attrs={'class': "form-control", 'placeholder': u'郵箱'}))
View
def publish(request): ret = {'status': False, 'data': '', 'error': '', 'summary': ''} if request.method == 'POST': request_form = PublishForm(request.POST) if request_form.is_valid(): request_dict = request_form.clean() print request_dict ret['status'] = True else: error_msg = request_form.errors.as_json() ret['error'] = json.loads(error_msg) return HttpResponse(json.dumps(ret))
在Web應用程序中開發編寫功能時,時經常使用到獲取數據庫中的數據並將值初始化在HTML中的標籤上。
一、Form
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() city = fields.ChoiceField( choices=((1, '上海'), (2, '北京'),), widget=widgets.Select )
二、Views
from django.shortcuts import render, redirect from .forms import MyForm def index(request): if request.method == "GET": values = {'user': 'root', 'city': 2} obj = MyForm(values) return render(request, 'index.html', {'form': obj}) elif request.method == "POST": return redirect('http://www.google.com') else: return redirect('http://www.google.com')
三、HTML
<form method="POST" enctype="multipart/form-data"> {% csrf_token %} <p>{{ form.user }} {{ form.user.errors }}</p> <p>{{ form.city }} {{ form.city.errors }}</p> <input type="submit"/> </form>
實例:
編輯學生列表
def edit_student(request,nid): if request.method=='GET': row=models.Student.objects.filter(id=nid).values('name','email','age','cls_id').first() obj=StudentForm(initial=row) # 編輯學生時GET請求時默認爲以前的數據。 return render(request,'edit_student.html',{'obj':obj,'nid':nid}) else: obj=StudentForm(request.POST) if obj.is_valid(): models.Student.objects.filter(id=nid).update(**obj.cleaned_data) return redirect('/student_list/') return render(request,'edit_student.html',{'obj':obj,'nid':nid})
其餘的保留上一次數據,相似的方法。
1.簡單擴展
利用Form組件自帶的正則擴展:
a. 方式一
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( error_messages={'invalid': '...'}, #錯誤提示 validators=[RegexValidator(r'^[0-9]+$', '請輸入數字'), RegexValidator
b. 方式二
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.RegexField(r'^[0-9]+$',error_messages={'invalid': '...'})
2.基於源碼流程
a. 單字段
from django.core.exceptions import NON_FIELD_ERRORS, ValidationError class AjaxForm(forms.Form): username = fields.CharField() user_id = fields.IntegerField( widget=widgets.Select(choices=[(0,'alex'),(1,'egon'),(2,'xyp'),]) ) # 自定義方法 clean_字段名 # 必須返回值self.cleaned_data['username'] # 若是出錯:raise ValidationError('用戶名已存在') def clean_username(self): v = self.cleaned_data['username'] if models.UserInfo.objects.filter(username=v).count(): # 總體錯了 # 本身詳細錯誤信息 raise ValidationError('用戶名已存在') return v def clean_user_id(self): return self.cleaned_data['user_id']
b. 總體錯誤驗證
class AjaxForm(forms.Form): username = fields.CharField() user_id = fields.IntegerField( widget=widgets.Select(choices=[(0,'alex'),(1,'egon'),(2,'xyp'),]) ) # 自定義方法 clean_字段名 # 必須返回值self.cleaned_data['username'] # 若是出錯:raise ValidationError('用戶名已存在') def clean_username(self): v = self.cleaned_data['username'] if models.UserInfo.objects.filter(username=v).count(): # 總體錯了 # 本身詳細錯誤信息 raise ValidationError('用戶名已存在') return v def clean_user_id(self): return self.cleaned_data['user_id'] def clean(self): value_dict = self.cleaned_data v1 = value_dict.get('username') v2 = value_dict.get('user_id') if v1 == 'root' and v2==1: raise ValidationError('總體錯誤信息') return self.cleaned_data
c、_post_clean 支持自定製方法
clean方法已經完成所有自定製了,因此_post_clean不經常使用