我在这里尝试使用“记住我”选项登录,但是此代码无法正常工作。如果未选中“ remember_me”复选框,则它不会登录;如果还选中了“记住我”选项,则它将登录但注销后,登录表单中还没有用户名和密码。我该如何实现Remember_me选项,还有更好的主意吗?
forms.py
from django import forms
class LoginForm(forms.Form):
username = forms.CharField(max_length=100)
password = forms.CharField(widget=forms.PasswordInput)
remember_me = forms.BooleanField()
模板
<form action="" method="post" class="form-signin">
{% csrf_token %}
<input type="text" class="form-control mb-2" name='username' placeholder="Username" required autofocus>
<input type="password" class="form-control mb-2" name='password' placeholder="Password" required>
<button class="btn btn-lg btn-primary btn-block mb-20" type="submit">Sign in</button>
<div class="checkbox float-left">
<input type="checkbox" name="remember_me" id="basic_checkbox_1" >
<label for="basic_checkbox_1">Remember me</label>
</div>
<a href="#" class="float-right">Need help?</a>
</form>
views.py
if request.method == 'POST':
form = LoginForm(request.POST or None)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
remember_me = form.cleaned_data['remember_me']
user = authenticate(request,username=username,password=password)
if user:
login(request,user)
if not remember_me:
request.session.set_expiry(0)
redirect_url = request.GET.get('next', 'home')
messages.success(request, 'logged in.')
return redirect(redirect_url)
else:
messages.error(request,'Invalid username or password')
else:
form = LoginForm()
return render(request,'login.html',{'form':form})
答案 0 :(得分:0)
您一切正常。当用户选中记住我时,您必须使用permanent/persistence cookies(这是django的默认行为)。如果用户未选中记住我,则必须使用session cookies。 永久性/持久性COOKIES 有有效期,会话COOKIES 没有有效期。当用户关闭浏览器时,会话COOKIES 被删除。 request.session.set_expiry(0)
这将帮助您设置会话COOKIES 。