1.urls.py中的代码:
urlpatterns=[
path('fmindex.html/',fm.fmindex)
]
2.index.html中代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% for item in obj %}
{{ item.user }} {{ item.email }}
{% endfor %}
</body>
</html>
3.fm.py中代码:
#_author:来童星
#date:2020/5/5
from django.shortcuts import render,HttpResponse
from app01 import models
from django import forms
from django.forms import fields
from django.core.exceptions import ValidationError
class UserInfo(forms.Form):
username=fields.CharField(label='用户名')
email=fields.EmailField(label='密码')
# def clean_username(self):
#
# value = self.cleaned_data['username']
# if value == 'root':
# return value
# else:
# raise ValidationError('你不是我的...')
def clean(self):
v1 = self.cleaned_data['username']
v2 = self.cleaned_data['email']
if v1 == "root" and v2 == "root@live.com":
pass
else:
raise ValidationError('用户名或邮箱错误!!!')
return self.cleaned_data
# def _post_clean(self):
# v1 = self.cleaned_data['username']
# v2 = self.cleaned_data['email']
# if v1 == "root" and v2 == "root@live.com":
# pass
# else:
# self.add_error("__all__", ValidationError('用户名或邮箱错误...'))
def fmindex(request):
if request.method == "GET":
obj = UserInfo()
return render(request,'fmindex.html',{'obj': obj})
elif request.method == "POST":
obj = UserInfo(request.POST)
obj.is_valid()
# data = obj.clean()
# obj.cleaned_data
# print(obj.errors)
return render(request, 'fmindex.html', {'obj': obj})
运行结果:
(1)定义
clean函数的结果:
(2)定义
_post_clean效果
(3)定义
clean_username函数的结果: