python - Django中自己编写的登入模块记住状态的问题
巴扎黑
巴扎黑 2017-04-18 09:25:29
0
1
330

没有使用自带的auth。我自己写了一个登入界面和views,但是如何记住你的状态?然后查了官方文档,说要使用@login_required,但是需要使用authenticate,因为它通过is_authenticated()来判断的。我是不是也要自己写一个装饰器呢?如果是怎么写。结合我views中产成的session来判断?还是怎么来完成?谢谢

views cide

测试登入状态的代码

巴扎黑
巴扎黑

reply all(1)
Ty80

Login:

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})

Operation functions that require login verification:
Just use django’s @login_required modification before the function

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)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template