首頁  >  問答  >  主體

python - django 里自定义的 login 方法,如何使用 login_required()

根据 官方文档 写了个自定义的 login 方法如下:

from django.contrib.auth import authenticate, login

def my_login(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username, password=password)
    if user is not None:
        login(request, user)
        # Redirect to a success page.
        ...
    else:
        # Return an 'invalid login' error message.
        ...

那么,在如何配合 @login_required 装饰器通过我自定义的 my_login() 方法进行登录呢?

PHP中文网PHP中文网2741 天前912

全部回覆(3)我來回復

  • ringa_lee

    ringa_lee2017-04-18 10:30:38

    在其他方法上加@login_required,request.user沒有就跳到登入頁
    你的登入post方法呼叫my_login不就行了

    回覆
    0
  • 迷茫

    迷茫2017-04-18 10:30:38

    http://python.usyiyi.cn/djang...

    回覆
    0
  • 大家讲道理

    大家讲道理2017-04-18 10:30:38

    裝飾器是用來放在其他view函數頭,來截斷請求判斷目前請求的是否是登入的,若不加便不會有這個判斷。
    而你定義的登入view函數,是一個用來使用戶登入的view函數,在這個函數裡把使用者的屬性綁定在了request 這個物件上,作為使用者登入標誌。

    純手機打字,望有幫助!

    回覆
    0
  • 取消回覆