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

如何在Django默认用户模型中新增matricule字段实现身份认证需求

在Django默认用户模型中新增matricule字段并实现对应身份认证的操作步骤

1 创建自定义用户模型

在你项目对应应用的models.py文件中继承Django官方推荐的AbstractUser类扩展用户字段:

from django.db import models
from django.contrib.auth.models import AbstractUser

class CustomUser(AbstractUser):
    # 可根据业务需求调整字段长度、是否允许为空等属性,用作登录凭据建议加unique唯一约束
    matricule = models.CharField(max_length=20, unique=True, verbose_name="工号/学号")

注意:如果你已经在生产环境执行过初始迁移、无法清空原有迁移记录,可参考文末的老项目兼容方案

2 配置项目全局用户模型

在项目根目录的settings.py中添加配置,指定全局使用你自定义的用户模型:

# 替换成你自己的应用名+自定义用户类名
AUTH_USER_MODEL = "你的应用名.CustomUser"

该配置必须在第一次执行migrate迁移命令前完成,否则会出现迁移依赖冲突

3 生成并执行数据库迁移

依次运行以下命令完成表结构更新:

  • python manage.py makemigrations
  • python manage.py migrate

4 自定义认证后端支持matricule登录

在应用内新建auth_backends.py文件,编写支持matricule校验的认证逻辑:

from django.contrib.auth.backends import ModelBackend
from django.contrib.auth import get_user_model
from django.db.models import Q

User = get_user_model()

class MatriculeAuthBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            # 这里同时支持用户名、matricule两种方式登录,不需要可以删掉Q(username=username)条件
            user = User.objects.get(Q(username=username) | Q(matricule=username))
        except User.DoesNotExist:
            return None
        if user.check_password(password) and self.user_can_authenticate(user):
            return user
        return None

之后在settings.py中注册这个自定义认证后端:

AUTHENTICATION_BACKENDS = [
    # 替换成你自己的应用名+认证后端类路径
    "你的应用名.auth_backends.MatriculeAuthBackend",
    # 不需要保留原用户名密码登录的话可以删掉下面这行
    "django.contrib.auth.backends.ModelBackend",
]

5 功能验证

后续调用Django原生的authenticate方法时,传入matricule值即可完成校验:

from django.contrib.auth import authenticate

# 第一个参数username填matricule的值即可
user = authenticate(username="用户的matricule值", password="用户密码")
if user:
    # 认证成功的业务逻辑
else:
    # 认证失败的业务逻辑

老项目兼容方案:无法修改原有用户模型时,可通过关联表扩展字段:

from django.db import models
from django.contrib.auth.models import User

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile")
    matricule = models.CharField(max_length=20, unique=True)

之后修改自定义认证后端的查询逻辑,关联UserProfile表查询matricule即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 21:18:03