You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决Django REST Framework中simplejwt错误翻译失效问题?

解决simpleJWT错误信息翻译问题

方法一:自定义视图重写错误信息

继承TokenObtainPairView,在验证失败时替换目标错误信息为中文:

from rest_framework_simplejwt.views import TokenObtainPairView
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework.exceptions import AuthenticationFailed

class CustomTokenObtainPairSerializer(TokenObtainPairSerializer):
    def validate(self, attrs):
        try:
            return super().validate(attrs)
        except AuthenticationFailed as e:
            if e.detail == "No active account found with the given credentials":
                raise AuthenticationFailed("未找到匹配的有效账户")
            raise e

class CustomTokenObtainPairView(TokenObtainPairView):
    serializer_class = CustomTokenObtainPairSerializer

更新urls.py中的配置:

urlpatterns = [
    path('token/', CustomTokenObtainPairView.as_view()),
]

方法二:通过Django翻译系统覆盖默认消息

  1. 在项目根目录创建locale/zh_Hans/LC_MESSAGES目录(适配简体中文)
  2. 在该目录下创建django.po文件,写入:
msgid "No active account found with the given credentials"
msgstr "未找到匹配的有效账户"
  1. 用msgfmt编译成二进制翻译文件:
msgfmt locale/zh_Hans/LC_MESSAGES/django.po -o locale/zh_Hans/LC_MESSAGES/django.mo
  1. 确保Django配置文件中开启国际化并指定翻译文件路径:
LANGUAGE_CODE = 'zh-hans'
USE_I18N = True
LOCALE_PATHS = [
    os.path.join(BASE_DIR, 'locale'),
]

方法三:直接修改源码(不推荐)

找到simpleJWT包内对应抛出错误的文件(如exceptions.py或验证逻辑文件),直接将目标英文错误信息替换为中文。但后续包版本更新会覆盖修改,因此不建议使用。

内容的提问来源于stack exchange,提问作者Przemek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 13:12:18