路由设置
- 设置路由,(路由设置有CBV和FBV,下面是使用的CBV)
1 url(r'^login/', views.LoginView.as_view()),
新建视图、用户鉴权
- 编写view,需要导入 from django.views.generic.base import View,新建的View需要继承View
- 使用auth.authenticate()用户鉴权
- 使用auth.login(),给某个已认证的用户附加上session id等信息,在前端通过request.user,使用用户信息。
1 from django.views.generic.base import View 2 # 导入authenticate用户鉴权使用,login保存登录用户信息 3 from django.contrib.auth import authenticate,login 4 5 6 # 新建视图类,必须继承View 7 class LoginView(View): 8 9 # 定义get方法,用户请求方式为get,自动执行该方法 10 def get(self,request): 11 return render(request, 'login.html') 12 13 # 定义pot方法,用户请求方式为pot,自动执行该方法 14 def post(self,request): 15 # 这边是使用form组件, 16 login_form = LoginForm(request.POST) 17 if login_form.is_valid(): 18 user_name = request.POST.get('username','') 19 pass_word = request.POST.get('password','') 20 # 使用authenticate进行用户鉴权,两个字段必须写username、password 21 user = authenticate(username=user_name,password=pass_word) 22 # 用户鉴权通过后,user会有值,若是鉴权失败为Null 23 if user: 24 login(request,user) 25 return render(request,'index.html') 26 else: 27 return render(request, 'login.html', {'msg': "用户名或者密码错误"}) 28 else: 29 return render(request,'login.html',{'login_form':login_form.errors})
增加邮箱验证方式
- 重写authenticate方法,支持邮箱验证
1 # 导入ModelBackend 2 from django.contrib.auth.backends import ModelBackend 3 4 # 定义类CustomBackend,必须继承ModelBackend 5 class CustomBackend(ModelBackend): 6 # 重写authenticate方法,增加email验证 7 def authenticate(self, request, username=None, password=None, **kwargs): 8 try: 9 user = UserProlfile.objects.get(Q(username = username)|Q(email=username)) # 实现并级查询 10 if user.check_password(password): 11 return user 12 13 except Exception as e: 14 return None 15 # 在项目的settings.py文件中配置 16 # 支持邮箱验证 17 AUTHENTICATION_BACKENDS=( 18 'users.views.CustomBackend', 19 )
- Forms组件使用,后面补充,
参照:https://www.cnblogs.com/xiugeng/p/9299083.html