def login(request, user, backend=None):
session_auth_hash = ''
if user is None:
user = request.user
if hasattr(user, 'get_session_auth_hash'):
session_auth_hash = user.get_session_auth_hash()
if SESSION_KEY in request.session:
if _get_user_session_key(request) != user.pk or (
session_auth_hash and
not constant_time_compare(request.session.get(HASH_SESSION_KEY, ''), session_auth_hash)):
request.session.flush()
else:
request.session.cycle_key()
......
从上述代码可以看出,该方法接受一个 HttpRequest 参数和一个 User 参数。如果使用 login 定义登录视图就会非常简单,它的应用代码如下所示:
from django.contrib.auth import login,authenticate
def login_views(request):
username=request.POST("username")
password=request.POST("password")
#调用 authenticate对user进行认证
user=authenticate(username=username,password=password)
if user:
#调用auth的login api
login(request,user)
pass
else:
pass
是不是极大的简化了登录视图的定义过程呢?因为 Auth login 这个 API 帮我们已经帮组我们完成基本的登录逻辑,我们只需要获取到用户输入的数据,对这些数据进行校验即可。django/contrib/auth/views.py
它的类名为 LoginView,定义如下所示:
class LoginView(SuccessURLAllowedHostsMixin, FormView):
"""
Display the login form and handle the login action.
"""
form_class = AuthenticationForm
authentication_form = None
redirect_field_name = REDIRECT_FIELD_NAME
template_name = 'registration/login.html'
redirect_authenticated_user = False
extra_context = None
我们对其中涉及的变量做一些简单的介绍:
LOGIN_REDIRECT_URL="/index/update_book/
这里我们还需要使用 CBV 类视图的方式,定义 URL 模式,如下所示:path('login/',LoginView.as_view(template_name="index/login.html"))
然后我们在 inedx/templates/index 中创建 login.html 代码如下所示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户登录页面</title>
</head>
<body>
<form action="" method="post">
<table>
{{ form }}
</table>
<!-- 防止 CSRF 攻击-->
{% csrf_token %}
<input type="submit" value="提交">
</form>
</body>
</html>
最后我们就可以在浏览器地址栏进行访问了,输入 127.0.0.1:8000/login/ 会得到如下返回:
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有