【问题标题】:How to make token authentication redirect to a url instead of showing an error message in json?如何使令牌身份验证重定向到 url 而不是在 json 中显示错误消息?
【发布时间】:2022-01-16 21:31:44
【问题描述】:
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
}

如果出现错误 401 Unauthorized,我需要令牌身份验证以重定向到 url 而不是在 json 中显示错误消息:

{ 
"detail": "Authentication credentials were not provided."
}

【问题讨论】:

  • 您确定需要这个吗? DRF 端点不应该由用户自己访问;前端应用程序代码必须调用它们。

标签: django django-rest-framework


【解决方案1】:

您可以做的是从视图中捕获响应的状态代码并重定向 对于类视图中的 get 方法:

def get(self, request):
    res = super().get(request)
    if res.status_code == 401:
        redirect('somewhere')

【讨论】:

    猜你喜欢
    • 2019-07-27
    • 1970-01-01
    • 2016-06-08
    • 2020-06-03
    • 2016-04-10
    • 2016-01-20
    • 1970-01-01
    • 2015-11-11
    • 1970-01-01
    相关资源
    最近更新 更多