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

基于DRF的自定义一对一用户模型:邮箱+密码Token认证求助

实现自定义User模型的邮箱+密码Token认证

没问题,我来帮你一步步搞定适配自定义User模型的Token认证,刚好你的模型用邮箱作为唯一标识,咱们针对性调整就行:

1. 基础配置(先把环境搭好)

首先确保你已经装了Django REST Framework(DRF),然后在settings.py里做这些配置:

# settings.py
INSTALLED_APPS = [
    # 你的其他应用...
    'rest_framework',
    'rest_framework.authtoken',  # 用来生成和管理Token
]

# 指定你的自定义用户模型(替换成你的app名)
AUTH_USER_MODEL = 'your_app.User'

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',  # 启用Token认证
    ],
}

2. 自定义Token获取视图

DRF默认的Token登录视图是找username字段的,但你的User模型用email作为USERNAME_FIELD,所以得自己写个视图适配:

# views.py
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.response import Response
from rest_framework import status
from django.contrib.auth import authenticate

class EmailTokenObtainView(ObtainAuthToken):
    def post(self, request, *args, **kwargs):
        # 从请求里拿邮箱和密码
        email = request.data.get('email')
        password = request.data.get('password')
        
        # 这里的username参数会自动对应你设置的USERNAME_FIELD(也就是email)
        user = authenticate(request, username=email, password=password)
        
        if user:
            # 获取或创建用户的Token(如果是第一次登录就新建,否则返回已有的)
            token, created = user.auth_token.get_or_create()
            return Response({
                'token': token.key,
                'user_id': user.pk,
                'email': user.email
            })
        else:
            return Response({
                'error': '邮箱或密码不正确'
            }, status=status.HTTP_400_BAD_REQUEST)

3. 配置URL路由

把自定义的Token视图加到路由里,方便前端调用:

# urls.py(项目或app的urls都可以)
from django.urls import path
from .views import EmailTokenObtainView

urlpatterns = [
    # 你的其他路由...
    path('api/token/', EmailTokenObtainView.as_view(), name='get_token'),
]

4. 确认DojoMaster的接收器正常

你已经有了DojoMaster和post_save接收器,这里再给个标准写法确保没问题,避免用户创建时关联模型出问题:

# models.py
from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=User)
def create_dojo_master(sender, instance, created, **kwargs):
    if created:
        DojoMaster.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_dojo_master(sender, instance, **kwargs):
    instance.dojomaster.save()

5. 测试认证流程

现在你可以用POST请求访问/api/token/,请求体传JSON格式的邮箱和密码:

{
    "email": "test@example.com",
    "password": "your_password"
}

验证成功会返回Token信息,之后在需要认证的API请求头里加上Authorization: Token <你的token>,就能正常访问需要权限的接口了。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:07:52