def post(self, request): # 验证提交数据是否合法 # 如果接收session中的id id = request.session.get('id') data = request.POST form = NewpwdForm(data) if form.is_valid(): if form.check_password(request): # 对新密码加密 new_password = hash_password( form.cleaned_data.get('new_password')) # 通过id更新对应用户密码 User.objects.filter(id=id).update(password=new_password) return redirect('user:个人中心') else: context = { 'data': data, 'form': form, } return render(request, 'user/password.html', context=context) else: context = { 'data': data, 'form': form, } return render(request, 'user/password.html', context=context)
def check_password(self, request): id = request.session.get('id') password = hash_password(self.cleaned_data.get('password')) result = User.objects.filter(pk=id, password=password).exists() if result: return True else: self.add_error('password', '密码输入错误') return False
def post(self, request): # post请求获取参数 data = request.POST form = GetPasswordForm(data) if form.is_valid(): # 操作数据库,根据手机号更改新密码 phone_num = form.cleaned_data.get('phone_num') password = hash_password(form.cleaned_data.get('password')) User.objects.filter(phone_num=phone_num).update(password=password) return redirect('user:登录') else: context = {'form': form} return render(request, 'user/forgetpassword.html', context=context)
def clean(self): phone_name = self.cleaned_data.get('phone_num') password = self.cleaned_data.get('password') try: user = User.objects.get(phone_num=phone_name) except User.DoesNotExist: raise forms.ValidationError({'phone_num': '账号不存在'}) if user.password != hash_password(password): raise forms.ValidationError({'password': '******'}) else: # 建立一个user对象到清洗数据上 self.cleaned_data['user'] = user return self.cleaned_data
def post(self, request): data = request.POST form = RegModelForm(data) if form.is_valid(): # 验证通过保存数据,并跳转到登录页面 user = User() user.phone_num = form.cleaned_data.get('phone_num') user.password = hash_password(form.cleaned_data.get('password')) user.save() # 添加一对一用户信息表 id = User.objects.get( phone_num=form.cleaned_data.get('phone_num')).pk UserInfo.objects.create(user_id=id) return redirect('user:登录') else: # 验证失败返回提示错误信息 return render(request, 'user/reg.html', {'form': form})