首页 > 解决方案 > 如何在 django shell 中以现有用户身份登录

问题描述

在 django shell 中,我想调试一个特定的 api 调用,并且要使资源正常工作,应该登录。

from django.test import  Client
from urllib.parse import urlsplit, parse_qsl

client = Client()
client.login(username='my_username', password='my_password')
# I also tried client.force_login() without success

url_data = urlsplit(url)
r = client.get(path=url_data.path, data=parse_qsl(url_data.query))

# r is <HttpUnauthorized status_code=401, "text/html; charset=utf-8">

编辑:我说的是具有真实凭据的真实环境(预生产)

如何正确登录?

标签: django

解决方案


尝试

from django.contrib.auth import authenticate
user = authenticate(username='john', password='secret')
if user is not None:
    # A backend authenticated the credentials
else:
    # No backend authenticated the credentials

https://docs.djangoproject.com/en/3.1/topics/auth/default/#authenticating-users


推荐阅读