HTML表单是网站交互性的经典方式。
HTTP 请求
HTTP协议以"请求-回复"的方式工作。客户发送请求时,可以在请求中附加数据。服务器通过解析请求,就可以获得客户传来的数据,并根据URL来提供特定的服务。
- GET方法
- POST方法
以下为半成品:
# 注册页面手机号验证
def mobile_validate(value):
mobile_re = re.compile(r'^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$')
value = str(value)
if not mobile_re.match(value):
raise forms.ValidationError('手机号码格式错误')
class RegisterForm(forms.Form):
username = forms.CharField(
error_messages={'required': '用户名不能为空', 'min_length': '最小长度为4', 'max_length': '最大长度为30'},
max_length=30,
min_length=4,
)
password = forms.CharField(
error_messages={'required': '密码不能为空'}
)
password_again = forms.CharField(
error_messages={'required': '密码不能为空',}
)
email = forms.EmailField(
required=False,
error_messages={'invalid': '邮箱格式错误'}
)
phone = forms.IntegerField(validators=[mobile_validate],
error_messages={'required': '手机号不能为空', 'invalid': '必须输入数字'}
)
roles = Role.objects.all().values_list('id', 'role_name')
role = forms.CharField(
error_messages={'required': '角色不能为空'},
widget=forms.widgets.Select(choices=roles, attrs={'class': 'c1'}))
marry_choice = (
('0', '男'),
('1', '女'),
('2', '已婚'),
('3', '未婚'),
)
marry = forms.MultipleChoiceField(
error_messages={'required': '选择不能为空'},
choices=marry_choice, widget=forms.CheckboxSelectMultiple())
favors = Favor.objects.all().values_list('id', 'favor_name')
favor = forms.CharField(
error_messages={'required': '爱好不能为空'},
widget=forms.widgets.Select(choices=favors, attrs={'class': 'c1', 'multiple': 'multiple'}))
code = forms.CharField(
error_messages={'required': '验证码不能为空'}
)
# 自定义验证 验证password
def clean_password(self):
cleaned_data = super(RegisterForm, self).clean()
user_data = cleaned_data.get('password')
if user_data == 'XXX':
raise forms.ValidationError(u'密码太简单了')
return user_data
# 验证两次输入的密码是否一致
def clean_password_again(self):
password = self.cleaned_data['password']
password_again = self.cleaned_data['password_again']
if password != password_again:
raise forms.ValidationError('两次密码不一致')
return password_again
def __init__(self, *args, **kwargs):
super(RegisterForm, self).__init__(*args, **kwargs)
self.fields['role'] = forms.CharField(
widget=forms.widgets.Select(choices=Role.objects.all().values_list('id', 'role_name'), attrs={'class': 'c1'})
)
self.fields['favor'] = forms.CharField(
widget=forms.widgets.Select(choices=Favor.objects.all().values_list('id', 'favor_name'),
attrs={'class': 'c1'})
)
# 验证选择婚姻是否正确
def clean_marry(self):
data_list = self.cleaned_data['marry']
if len(data_list) == 2:
if '0' and '1' in data_list:
raise forms.ValidationError('男女选择有误!')
elif '2' and '3' in data_list:
raise forms.ValidationError('婚姻选择有误!')
else:
return data_list
else:
raise forms.ValidationError('请选择男女和婚姻!')
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户注册</title>
<link rel="stylesheet" type="text/css" href="/statics/css/one.css">
</head>
<body>
<div class="register-page">
<div class="mid-css">
<form method="post" action="/register/">
<div class="commons-css">
<span class="register-span">用户名:</span>
<input type="text" name="username" placeholder="请输入用户名">
<span class="error-info">{{ errors.username.0 }}</span>
</div>
<div class="commons-css">
<span class="register-span">密码:</span>
<input type="text" name="password" placeholder="请输入密码">
<span class="error-info">{{ errors.password.0 }}</span>
</div>
<div class="commons-css">
<span class="register-span">确认密码:</span>
<input type="text" name="password_again" placeholder="请输入密码">
<span class="error-info">{{ errors.password_again.0 }}</span>
</div>
<div class="commons-css">
<span class="register-span">邮箱:</span>
<input type="text" name="email" placeholder="请输入邮箱">
<span class="error-info">{{ errors.email.0 }}</span>
</div>
<div class="commons-css">
<span class="register-span">手机号:</span>
<input type="text" name="phone" placeholder="请输入手机号">
<span class="error-info">{{ errors.phone.0 }}</span>
</div>
<div class="commons-css">
<span class="register-span">角色:</span>
{{ form.role }}
<span class="error-info">{{ errors.role.0 }}</span>
</div>
<div class="favor-css ClearFloat">
<span class="favor-span">婚姻状况:</span>
{{ form.marry }}
<span class="error-info">{{ errors.marry.0 }}</span>
</div>
<div class="commons-css">
<span class="register-span">爱好:</span>
{{ form.favor }}
<span class="error-info">{{ errors.favor.0 }}</span>
</div>
<div class="commons-css">
<span class="register-span">验证码:</span>
<input type="text" name="code" style="width: 150px">
<span class="span-code" onclick= "GetCode(this)" id="span">点击获取</span>
{% if errors.code.0 %}
<span class="error-info">{{ errors.code.0 }}</span>
{% else %}
<span class="error-info">{{ code_error.error_code_info }}</span>
{% endif %}
</div>
<div class="register-submit">
<input type="button" value="重置">
<input type="submit" value="注册">
</div>
</form>
</div>
</div>
<script type="text/javascript" src="/statics/js/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="/statics/js/one.js"></script>
</body>
</html>
后台处理
def register(request):
if request.method == 'POST':
register_obj = RegisterForm(request.POST)
ret = register_obj.is_valid()
if ret:
input_code = register_obj.cleaned_data['code']
old_code = request.session['code']
if input_code.upper() == old_code.upper():
request.session['is_login'] = True
print(register_obj.cleaned_data)
return HttpResponseRedirect('/manager/')
else:
error_code_info = {'error_code_info': '验证码输入错误'}
return render(request, 'forms/register.html', {'errors': register_obj.errors,
'code_error': error_code_info, 'form': register_obj})
else:
return render(request, 'forms/register.html', {'errors': register_obj.errors, 'form': register_obj})
else:
register_obj = RegisterForm()
return render(request, 'forms/register.html', {'form': register_obj})
页面效果