python - django sessions remember me
问题描述
I am new to django and have not found a question corresponding to my entry level. And I just can't figure out how to work with sessions. I want to make a checkbox on login to remember me. After I registered in settings SESSION_EXPIRE_AT_BROWSER_CLOSE = True, you need to enter your username and password after closing the browser. How do I change this parameter using the "remember me" checkbox? Thank you
views.py
def login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
return redirect('/')
else:
messages.info(request, 'invalid credentials')
return redirect('login')
else:
return render(request, 'prof/login.html')
login.html
<body>
<div class="text-center mt-5">
<form style="max-width: 480px; margin: auto" method="post">
{% csrf_token %}
<img
src="https://logodix.com/logo/1713894.jpg"
alt=""
width="120"
height="90"
class="d-inline-block mt-4 mb-4"
/>
<p class="hint-text mb-3">Please sign in</p>
<label class="sr-only" for="username"></label>
<input
type="login"
name="username"
class="form-control"
placeholder="username"
required
autofocus
/>
<label for="password" class="sr-only"></label>
<input
type="password"
name="password"
class="form-control mt-2"
placeholder="password"
/>
<div class="checkbox">
<label for="checkbox">
<input type="checkbox" name="checkbox" value="remember-me" /> remember
me
</label>
</div>
<div class="d-grid gap-2 mt-4">
<input type="Submit" class="btn btn-primary" value="sign in" />
</div>
</form>
<div class="messages">
{% for message in messages %}
<h3>{{message}}</h3>
{% endfor %}
</div>
解决方案
def login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = auth.authenticate(username=username, password=password)
try:
remember = request.POST['remember_me']
if remember:
settings.SESSION_EXPIRE_AT_BROWSER_CLOSE = False
except:
is_private = False
settings.SESSION_EXPIRE_AT_BROWSER_CLOSE = True
if user is not None:
auth.login(request, user)
return redirect('/')
else:
messages.info(request, 'invalid credentials')
return redirect('login')
else:
return render(request, 'prof/login.html')
推荐阅读
- php - 如何限制数组中的数组
- python - 从 Python 中的打印输出中删除用户输入
- java - 如何加密 InputStream 中的 Excel 并写入 OutputStream?
- java - Java str.replaceAll() 不将 \R 识别为字符类的一部分
- javascript - javascript:如何在特定时间后停止调用函数
- python - 如何让船在拍摄时不停止?
- python - 逗号出现在自定义 Ansible 查找插件返回的值中
- angular-material - mat-horizontal-stepper steps going out of view
- python - 如何修复滚动条,使其从上到下拉伸?
- c#-4.0 - c#中的二进制转换方法