表單的 error_messages
參數(shù)讓你覆蓋字段默認(rèn)的異常信息悉抵。其格式為一個(gè)字典衔瓮。
新建一個(gè)表單存捺,自定義他的錯(cuò)誤信息:
from django import forms
class TestForm(forms.Form):
# error_messages 是自定義的錯(cuò)誤信息
# required,表示輸入信息為空引發(fā)的錯(cuò)誤
# 另外 CharField 還有 max_length, min_length 兩種錯(cuò)誤信息類(lèi)型
name = forms.CharField(error_messages={'required': '請(qǐng)輸入名字'})
我們?cè)?shell 里面測(cè)試下這個(gè)表單:
from myApp.forms import TestForm
# 一個(gè) name 的值為空的表單
f = TestForm({'name':''})
# 打印自定義的錯(cuò)誤信息
f.errors
>>> {'name': ['請(qǐng)輸入名字']}
每個(gè)字段都定義了它自己的錯(cuò)誤信息铅碍,詳情參見(jiàn): 內(nèi)建字段
現(xiàn)在我們讓錯(cuò)誤信息出現(xiàn)在頁(yè)面润绵。
首先我們擴(kuò)展下表單的錯(cuò)誤信息,增加一個(gè)最大字段長(zhǎng)度的屬性:
from django import forms
class TestForm(forms.Form):
name = forms.CharField(
max_length = 10,
error_messages={
'required': '請(qǐng)輸入名字',
'max_length': '名字不能超過(guò)10個(gè)字符'
}
)
編寫(xiě) test.html :
<html>
<body>
<form action={% url 'test' %} method="post">
{% csrf_token %}
名字:<input type="text" name='name'>
{# 表單的錯(cuò)誤信息胞谈,如果表單沒(méi)有錯(cuò)誤授药,該字段是空的,不會(huì)顯示 #}
{{ form.errors.name }}
<input type="submit" value="提交">
</form >
</body>
</html>
網(wǎng)頁(yè)現(xiàn)在看起來(lái)像這樣的:
編寫(xiě)視圖函數(shù):
from django.shortcuts import render
from myApp.forms import TestForm
def test(request):
context = {}
if request.method == 'GET':
form = TestForm
if request.method == 'POST':
form = TestForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
context['form'] = form
return render(request, 'test.html', context)
else:
context['form'] = form
return render(request, 'test.html', context)
return render(request, 'test.html', context)
現(xiàn)在我們嘗試下輸入錯(cuò)誤的信息:
沒(méi)填寫(xiě)任何信息:
填寫(xiě)信息超過(guò)十個(gè)字符: