search

Home  >  Q&A  >  body text

python - Django中自己编写的登入模块记住状态的问题

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

views cide

测试登入状态的代码

巴扎黑巴扎黑2770 days ago339

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-04-18 09:27:29

    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)

    reply
    0
  • Cancelreply