Django:使用另一个项目对用户进行身份验证

问题描述 投票:0回答:1

我有两个django项目A和B,它们使用相同的用户模型。用户模型位于A中,并且B向A发送请求以进行用户身份验证,如下所示:

# Project B:
url = ...    # Project A's url
data = {'username':request.POST.get('username'),
        'password':request.POST.get('password')}

resp = requests.post(url, data=data)    # A authenticates with the username and password
if resp.text == 'True':
    # login the user: how?
    user = ...
else:
    # Login fails

我的问题:如何在B中创建经过身份验证的用户?

编辑:最初,我使用了两个“应用程序”,但我真正的意思是两个“项目”。抱歉。

django authentication
1个回答
0
投票

尝试将用户发送到登录页面并使其返回该页面需要登录。

因此,将返回页插入next变量中,例如:

# in App B
if request.user.is_authenticated :
    # some code
else:        
    return redirect('/accounts/login/?next=/maApp/myView')

然后在login页面中获得next并将其放入输入中,然后将用户返回到您的正确页面。

在您的登录表单中添加

<input type="hidden" name="next" value="{{ request.GET.next }}">

和在登录视图中

# in App A
def login:
   ...
   # after login process
   next_page = request.POST['next']
   if next_page != '':
       return redirect(next_page)
   else:
       #normal login
© www.soinside.com 2019 - 2024. All rights reserved.