文章目录
激动的心,颤抖的手,在键盘和鼠标间不断的游走,发现有好几天没更新了,这次先把用户及登录相关的部分写一下。毕竟千万系统平台都是从登录注册和用户开始的,整起来,还是老话,这版虽然有点简陋,但还是会更新的优化的,莫急莫急!!!
首先看下成果图
再来看下结构吧。。。
这里需要新建一个APP,既然是用户的注册登录就直接命名成user了
在views.py里写用户注册和登录的逻辑
这里涉及到以下几块的逻辑,分别是注册、登录、忘记密码、重置密码、后面还有个退出登录,这里我也尝试的加了一下,直接退出跳转到首页。
用户登录:
# 用户登录
def user_login(request):
"""
用户登录
"""
if request.user.is_authenticated: # 如果已登录就直接跳到主页
return HttpResponseRedirect(reverse("index"))
if request.is_ajax(): # 请求ajax则返回新的image_url和key
result = dict()
result['key'] = CaptchaStore.generate_key()
result['image_url'] = captcha_image_url(result['key'])
return JsonResponse(result)
if request.method == "POST":
login_form = UserForm(request.POST)
if login_form.is_valid():
username = login_form.cleaned_data['username']
password = login_form.cleaned_data['password']
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return HttpResponseRedirect(reverse("index"))
else:
return render(request, "users/login.html", {"login_form": login_form, "msg": "登录失败, 请检查用户名或者密码! "})
else:
return render(request, "users/login.html", {"login_form": login_form})
else:
hashkey = CaptchaStore.generate_key()
image_url = captcha_image_url(hashkey)
login_form = UserForm()
return render(request, "users/login.html",
{"login_form": login_form, "hashkey": hashkey, "image_url": image_url, })
用户注册:
# 用户注册
def register(request):
"""
用户注册
"""
if request.is_ajax(): # 请求ajax则返回新的image_url和key
result = dict()
result['key'] = CaptchaStore.generate_key()
result['image_url'] = captcha_image_url(result['key'])
return JsonResponse(result)
if request.method == "POST":
register_form = RegisterForm(request.POST)
if register_form.is_valid():
username = register_form.cleaned_data['username']
password1 = register_form.cleaned_data['password1']
password2 = register_form.cleaned_data['password2']
if password1 != password2:
msg = "两次输入的密码不同!"
return render(request, "users/register.html", {'register_form': register_form, 'msg': msg})
else:
same_user = UserProfile.objects.filter(username=username)
if same_user: # 用户名唯一
msg = '用户名已经存在,请重新选择用户名!'
return render(request, "users/register.html", {'register_form': register_form, 'msg': msg})
new_user = UserProfile()
new_user.username = username
new_user.password = make_password(password1) # 使用加密密
new_user.save()
return redirect('/login/') # 自动跳转到登录页面
else:
return render(request, "users/register.html", {'register_form': register_form})
else:
register_form = RegisterForm()
hashkey = CaptchaStore.generate_key()
image_url = captcha_image_url(hashkey)
return render(request, "users/register.html",
{'register_form': register_form, "hashkey": hashkey, "image_url": image_url, })
忘记密码:
# 重置密码(忘记密码)
def reset_password(request):
"""
密码重置
"""
if request.is_ajax(): # 请求ajax则返回新的image_url和key
result = dict()
result['key'] = CaptchaStore.generate_key()
result['image_url'] = captcha_image_url(result['key'])
return JsonResponse(result)
if request.method == "POST":
reset_pwd_form = ResetPwdForm(request.POST)
if reset_pwd_form.is_valid():
username = reset_pwd_form.cleaned_data['username']
password1 = reset_pwd_form.cleaned_data['password1']
password2 = reset_pwd_form.cleaned_data['password2']
if password1 != password2:
msg = "两次输入的密码不同!"
return render(request, "users/reset_password.html", {'reset_pwd_form': reset_pwd_form, 'msg': msg})
else:
user = UserProfile.objects.get(username=username)
user.password = make_password(password1)
user.save()
logout(request)
return redirect('/login/') # 自动跳转到登录页面
else:
reset_pwd_form = ResetPwdForm()
hashkey = CaptchaStore.generate_key()
image_url = captcha_image_url(hashkey)
return render(request, "users/reset_password.html",
{'reset_pwd_form': reset_pwd_form, "hashkey": hashkey, "image_url": image_url, })
@login_required(login_url='/users/login')
def reset_password1(request):
"""
登录后密码重置
"""
if request.is_ajax(): # 请求ajax则返回新的image_url和key
result = dict()
result['key'] = CaptchaStore.generate_key()
result['image_url'] = captcha_image_url(result['key'])
return JsonResponse(result)
if request.method == "POST":
reset_pwd_form = ResetPwdForm(request.POST)
if reset_pwd_form.is_valid():
username = reset_pwd_form.cleaned_data['username']
password1 = reset_pwd_form.cleaned_data['password1']
password2 = reset_pwd_form.cleaned_data['password2']
if password1 != password2:
msg = "两次输入的密码不同!"
return render(request, "users/reset_password.html", {'reset_pwd_form': reset_pwd_form, 'msg': msg})
else:
user = UserProfile.objects.get(username=username)
user.password = make_password(password1)
user.save()
return redirect('/login/') # 自动跳转到登录页面
else:
reset_pwd_form = ResetPwdForm()
hashkey = CaptchaStore.generate_key()
image_url = captcha_image_url(hashkey)
return render(request, "base.html",
{'reset_pwd_form': reset_pwd_form, "hashkey": hashkey, "image_url": image_url, })
重置密码:
# 登录号密码重置
@login_required(login_url='/users/login')
def reset_password1(request):
"""
登录后密码重置
"""
if request.is_ajax(): # 请求ajax则返回新的image_url和key
result = dict()
result['key'] = CaptchaStore.generate_key()
result['image_url'] = captcha_image_url(result['key'])
return JsonResponse(result)
if request.method == "POST":
reset_pwd_form = ResetPwdForm(request.POST)
if reset_pwd_form.is_valid():
username = reset_pwd_form.cleaned_data['username']
password1 = reset_pwd_form.cleaned_data['password1']
password2 = reset_pwd_form.cleaned_data['password2']
if password1 != password2:
msg = "两次输入的密码不同!"
return render(request, "users/reset_password.html", {'reset_pwd_form': reset_pwd_form, 'msg': msg})
else:
user = UserProfile.objects.get(username=username)
user.password = make_password(password1)
user.save()
return redirect('/login/') # 自动跳转到登录页面
else:
reset_pwd_form = ResetPwdForm()
hashkey = CaptchaStore.generate_key()
image_url = captcha_image_url(hashkey)
return render(request, "base.html",
{'reset_pwd_form': reset_pwd_form, "hashkey": hashkey, "image_url": image_url, })
退出登录:
# 用户退出登录
@login_required(login_url='/users/login')
def user_logout(request):
"""
用户退出
"""
logout(request)
return HttpResponseRedirect(reverse("index"))
写完这些接下来就是建库写入数据了
这一步需要在models.py和form.py完成
先创建一个用户表,再创建子表与它进行关联
models.py
class UserProfile(AbstractUser):
"""
用户表
"""
birthday = models.DateField(verbose_name="生日", null=True, blank=True)
mobile = models.CharField(max_length=11, null=True, blank=True)
def __str__(self):
return self.username
class Meta:
verbose_name = "用户"
verbose_name_plural = "用户"
form.py
class UserForm(forms.Form):
"""登录表单"""
username = forms.CharField(required=True, label="用户名", max_length=128,
widget=forms.TextInput(attrs={'class': 'form-control'}))
password = forms.CharField(required=True, label="密码", max_length=256,
widget=forms.PasswordInput(attrs={'class': 'form-control'}))
captcha = CaptchaField(label='验证码', error_messages={"invalid": "验证码错误"}, )
class RegisterForm(forms.Form):
"""注册表单"""
username = forms.CharField(label="用户名", max_length=128, widget=forms.TimeInput(attrs={'class': 'form-control'}))
password1 = forms.CharField(label="密码", max_length=256, widget=forms.PasswordInput(attrs={'class': 'form-control'}))
password2 = forms.CharField(label="确认密码", max_length=256,
widget=forms.PasswordInput(attrs={'class': 'form-control'}))
captcha = CaptchaField(label='验证码', error_messages={"invalid": "验证码错误"}, )
class ResetPwdForm(forms.Form):
"""
重置密码表单
"""
username = forms.CharField(label="用户名", max_length=128, widget=forms.TimeInput(attrs={'class': 'form-control'}))
password1 = forms.CharField(label="新密码", max_length=256,
widget=forms.PasswordInput(attrs={'class': 'form-control'}))
password2 = forms.CharField(label="确认新密码", max_length=256,
widget=forms.PasswordInput(attrs={'class': 'form-control'}))
captcha = CaptchaField(label='验证码', error_messages={"invalid": "验证码错误"}, )
接下来就需要对登录页就行渲染编写了,这里用到的还是bootstrap,后期会改成elementui
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Carbon - Admin Template</title>
<link rel="stylesheet" href="./vendor/simple-line-icons/css/simple-line-icons.css">
<link rel="stylesheet" href="./vendor/font-awesome/css/fontawesome-all.min.css">
<link rel="stylesheet" href="./css/styles.css">
</head>
<body>
<div class="page-wrapper flex-row align-items-center">
<div class="container">
<div class="row justify-content-center">
<div class="col-md-5">
<div class="card p-4">
<div class="card-header text-center text-uppercase h4 font-weight-light">
Login
</div>
<div class="card-body py-5">
<div class="form-group">
<label class="form-control-label">Email</label>
<input type="email" class="form-control">
</div>
<div class="form-group">
<label class="form-control-label">Password</label>
<input type="password" class="form-control">
</div>
<div class="custom-control custom-checkbox mt-4">
<input type="checkbox" class="custom-control-input" id="login">
<label class="custom-control-label" for="login">Check this custom checkbox</label>
</div>
</div>
<div class="card-footer">
<div class="row">
<div class="col-6">
<button type="submit" class="btn btn-primary px-5">Login</button>
</div>
<div class="col-6">
<a href="#" class="btn btn-link">Forgot password?</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="./vendor/jquery/jquery.min.js"></script>
<script src="./vendor/popper.js/popper.min.js"></script>
<script src="./vendor/bootstrap/js/bootstrap.min.js"></script>
<script src="./vendor/chart.js/chart.min.js"></script>
<script src="./js/carbon.js"></script>
<script src="./js/demo.js"></script>
</body>
</html>