这次我们完成后端注册页面的逻辑实现
新建forms.py文件进行表单验证
from django import forms
class RegisterForm(forms.Form):
username = forms.CharField(max_length=20, min_length=5, required=True, error_messages={"max_length": "用户名最常长度为20", "min_length": "用户名最短为5"})
password = forms.CharField(max_length=20, min_length=8, required=True, error_messages={"max_length": "密码最常长度为20", "min_length": "密码最短为8"})
password2 = forms.CharField(max_length=20, min_length=8, required=True)
mobile = forms.CharField(max_length=11, min_length=11, required=True)
sms_code = forms.CharField(max_length=6, min_length=6, required=True)
def clean(self):
cleaned_data = super().clean()
password = cleaned_data.get("password")
password2 = cleaned_data.get("password2")
if password != password2:
raise forms.ValidationError('两次密码不一致')
return cleaned_data
保存到数据库
class RegisterView(View):
"""提供用户注册页面"""
def get(self, request):
return render(request, 'register.html')
"""提供用户注册注册逻辑"""
def post(self, request):
# 校验参数
register_form = RegisterForm()
if register_form.is_valid():
username = register_form.cleaned_data.get('username')
password = register_form.cleaned_data.get('password')
mobile = register_form.cleaned_data.get('mobile')
# 保存到数据库中
try:
User.objects.create_user(password=password, username=username, mobile=mobile)
except Exception:
return render(request, 'register.html', {'register_errmsg': '注册失败'})
# 注册成功
return http.HttpResponse('注册成功,重定向到首页')