实现:表单验证
工程示例:
urls.py
from django.conf.urls import urlfrom django.contrib import adminfrom app01 import viewsurlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^f1.html$', views.f1),]
settings.py
STATIC_FILES_DIRS = ( os.path.join(BASE_DIR,'static'),)
views.py
from django.shortcuts import renderfrom django.shortcuts import redirectfrom django.shortcuts import HttpResponsefrom app01 import modelsfrom django import formsfrom django.forms import fieldsclass F1Form(forms.Form): user = fields.CharField( max_length=18, min_length=6, required=True, error_messages={'required': '用户名不能为空', 'max_length': '太长了', 'min_length': '太短了' } ) pwd = fields.CharField( required=True, min_length=32 ) age = fields.IntegerField( required=True, error_messages={ 'required': '邮箱不能为空', 'invalid': '邮箱格式错误', } ) email = fields.EmailField( required=True, min_length=8 )def f1(request): if request.method == 'GET': obj = F1Form() return render(request, 'f1.html', {'obj': obj}) else: obj = F1Form(request.POST) # 是否全部验证成功 if obj.is_valid(): # 用户提交的数据 print('验证成功', obj.cleaned_data) return redirect('http://www.baidu.com') else: print('验证失败', obj.errors) return render(request, 'f1.html', {'obj': obj})
f1.html
Title
注意事项: