没有使用自带的auth。我自己写了一个登入界面和views,但是如何记住你的状态?然后查了官方文档,说要使用@login_required,但是需要使用authenticate,因为它通过is_authenticated()来判断的。我是不是也要自己写一个装饰器呢?如果是怎么写。结合我views中产成的session来判断?还是怎么来完成?谢谢
views cide
测试登入状态的代码
PHP中文网2017-04-18 09:27:29
登入:
from django.contrib.auth import authenticate, login, logout
def log_in(request):
if request.method == 'GET':
form = LoginForm()
return render(request, 'login.html', {'form': form})
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data['uid']
password = form.cleaned_data['pwd']
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
url = request.POST.get('source_url','/focus')
return redirect(url)
else:
return render(request,'login.html', {'form':form, 'error': "password or username is not ture!"})
else:
return render(request, 'login.html', {'form': form})
需要登入驗證的操作函數:
在函數前使用 django的 @login_required 修飾就可以
from django.contrib.auth.decorators import login_required
@login_required
def log_out(request):
# 顺便把log_out给你写出来了
url = request.POST.get('source_url', '/focus/')
logout(request)
return redirect(url)