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

使用dj-rest-auth注册返回HTTP 204无内容问题求助

解决dj-rest-auth注册接口返回204且不生成Token的问题

以下是针对你遇到问题的具体排查和解决步骤:

1. 版本兼容性检查

不同版本的dj-rest-auth在注册后的Token生成逻辑上存在差异,作者仓库使用的旧版本默认会在注册时自动生成Token,而新版本可能取消了这一默认行为。

  • 查看作者仓库的requirements.txt,安装与之匹配的版本,执行命令:
    pip install dj-rest-auth==2.2.0 django-allauth==0.47.0
    
  • 安装完成后重启服务,测试注册接口是否恢复预期行为。

2. 添加Token生成信号

如果需要使用新版本的依赖,可通过Django信号实现用户创建时自动生成Token:

  • 在你的应用目录下创建signals.py文件,添加以下代码:
    from django.db.models.signals import post_save
    from django.contrib.auth.models import User
    from rest_framework.authtoken.models import Token
    from django.dispatch import receiver
    
    @receiver(post_save, sender=User)
    def create_auth_token(sender, instance=None, created=False, **kwargs):
        if created:
            Token.objects.create(user=instance)
    
  • 修改应用目录下的apps.py,在ready方法中导入信号:
    from django.apps import AppConfig
    
    class YourAppConfig(AppConfig):
        default_auto_field = 'django.db.models.BigAutoField'
        name = 'your_app_name'
    
        def ready(self):
            import your_app_name.signals
    
  • 在settings.py的INSTALLED_APPS中替换原应用名为上述配置类:
    INSTALLED_APPS = [
        # ...其他应用
        'your_app_name.apps.YourAppConfig',
    ]
    

3. 自定义注册序列化器

通过重写注册序列化器,确保用户创建后生成Token并返回201响应:

  • 创建自定义序列化器:
    from rest_auth.registration.serializers import RegisterSerializer
    from rest_framework.authtoken.models import Token
    
    class CustomRegisterSerializer(RegisterSerializer):
        def save(self, request):
            user = super().save(request)
            Token.objects.create(user=user)
            return user
    
  • 在settings.py中配置使用该序列化器:
    REST_AUTH_REGISTER_SERIALIZERS = {
        'REGISTER_SERIALIZER': 'your_app.serializers.CustomRegisterSerializer',
    }
    

4. 验证REST框架认证配置

确保settings.py中的REST_FRAMEWORK配置包含Token认证:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ],
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 07:57:20