1.初步视图:
users/views.py
class RegisterView(View): '''用户注册''' def get(self,request): return render(request,'register.html')
用户以get方式,直接返回注册页面
2设计路由:
# MxOnline/urls.py from users.views import RegisterView
path('register/',RegisterView.as_view(),name = 'register'),
修改index.html
点 “注册 ”应该跳到用户注册页面
<a style="color:white" class="fr registerbtn" href="/register/">注册</a>
<a style="color:white" class="fr loginbtn" href="/login/">登录</a>
修改register.html中的静态文件地址
{% load staticfiles %} <link rel="stylesheet" type="text/css" href="{% static 'css/reset.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'css/login.css' %}"> <script src="{% static 'js/jquery.min.js' %}" type="text/javascript"></script> <script src="{% static 'js/unslider.js' %}" type="text/javascript"></script> <script src="{% static 'js/validateDialog.js' %}" type="text/javascript"></script> <script src="{% static 'js/login.js' %}" type="text/javascript"></script>
验证码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
验证码库:django-simple-captcha,这里面有介绍这个第三方库的使用方法 安装: pip install django-simple-captcha Add captcha to the INSTALLED_APPS in your settings.py INSTALLED_APPS = [ 'captcha', ] Add an entry to your urls.py: urlpatterns = [ path('captcha/',include('captcha.urls')), ] 生成到数据库 python manage.py makemigrations python manage.py migrate
在注册页面显示验证码
定义我们的register form:
# users/forms.py from django import forms from captcha.fields import CaptchaField class LoginForm(forms.Form): '''登录验证表单''' username = forms.CharField(required=True) password = forms.CharField(required=True,min_length=5) class RegisterForm(forms.Form): '''注册验证表单''' email = forms.EmailField(required=True) password = forms.CharField(required=True,min_length=5) # 验证码 captcha = CaptchaField(error_messages={'invalid':'验证码错误'})
通过{{ register_form.captcha }}获取验证码
<div class="form-group marb8 captcha1 "> <label>验 证 码</label> {{ register_form.captcha }} </div>
视图逻辑:
# users/views.py from django.shortcuts import render from django.contrib.auth import authenticate,login from django.contrib.auth.backends import ModelBackend from .models import UserProfile,EmailVerifyRecord from django.db.models import Q from django.views.generic.base import View from .forms import LoginForm,RegisterForm from django.contrib.auth.hashers import make_password from utils.email_send import send_register_eamil #邮箱和用户名都可以登录 # 基础ModelBackend类,因为它有authenticate方法 class CustomBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): try: # 不希望用户存在两个,get只能有一个。两个是get失败的一种原因 Q为使用并集查询 user = UserProfile.objects.get(Q(username=username)|Q(email=username)) # django的后台中密码加密:所以不能password==password # UserProfile继承的AbstractUser中有def check_password(self, raw_password): if user.check_password(password): return user except Exception as e: return None class LoginView(View): '''用户登录''' def get(self,request): return render(request, 'login.html') def post(self,request): # 实例化 login_form = LoginForm(request.POST) if login_form.is_valid(): # 获取用户提交的用户名和密码 user_name = request.POST.get('username', None) pass_word = request.POST.get('password', None) # 成功返回user对象,失败None user = authenticate(username=user_name, password=pass_word) # 如果不是null说明验证成功 if user is not None: if user.is_active: # 只有注册激活才能登录 login(request, user) return render(request, 'index.html') else: return render(request, 'login.html', {'msg': '用户名或密码错误', 'login_form': login_form}) # 只有当用户名或密码不存在时,才返回错误信息到前端 else: return render(request, 'login.html', {'msg': '用户名或密码错误','login_form':login_form}) # form.is_valid()已经判断不合法了,所以这里不需要再返回错误信息到前端了 else: return render(request,'login.html',{'login_form':login_form}) # 激活用户 class ActiveUserView(View): def get(self, request, active_code): # 查询邮箱验证记录是否存在 all_record = EmailVerifyRecord.objects.filter(code = active_code) if all_record: for record in all_record: # 获取到对应的邮箱 email = record.email # 查找到邮箱对应的user user = UserProfile.objects.get(email=email) user.is_active = True user.save() # 验证码不对的时候跳转到激活失败页面 else: return render(request,'active_fail.html') # 激活成功跳转到登录页面 return render(request, "login.html", ) class RegisterView(View): '''用户注册''' def get(self,request): register_form = RegisterForm() return render(request,'register.html',{'register_form':register_form}) def post(self,request): register_form = RegisterForm(request.POST) if register_form.is_valid(): user_name = request.POST.get('email', None) # 如果用户已存在,则提示错误信息 if UserProfile.objects.filter(email = user_name): return render(request, 'register.html', {'register_form':register_form,'msg': '用户已存在'}) pass_word = request.POST.get('password', None) # 实例化一个user_profile对象 user_profile = UserProfile() user_profile.username = user_name user_profile.email = user_name user_profile.is_active = False # 对保存到数据库的密码加密 user_profile.password = make_password(pass_word) user_profile.save() send_register_eamil(user_name,'register') return render(request,'login.html') else: return render(request,'register.html',{'register_form':register_form}) views.py所以代码