You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
DjangoBlog/accounts/models.py

60 lines
3.3 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

from django.contrib.auth.models import AbstractUser
from django.db import models
from django.urls import reverse
from django.utils.timezone import now
from django.utils.translation import gettext_lazy as _
from djangoblog.utils import get_current_site # 导入项目公共工具函数(获取当前站点域名)
# 模块级注释——accounts应用的核心数据模型文件
# 定义自定义用户模型`BlogUser`继承Django内置`AbstractUser`
# 扩展业务所需的自定义字段(如昵称、创建时间、创建来源),
# 并重写核心方法以适配项目业务逻辑如用户URL生成、字符串表示
# Create your models here.
class BlogUser(AbstractUser):
"""
自定义用户模型继承Django内置`AbstractUser`(保留用户名、密码、邮箱等核心字段)
扩展项目所需的业务字段,适配博客系统的用户管理需求,支持国际化配置
"""
# 昵称字段支持国际化标签最大长度100允许空值用户可选择不设置昵称
nickname = models.CharField(_('nick name'), max_length=100, blank=True)
# 创建时间字段:支持国际化标签,默认值为当前时间,记录用户注册时间
creation_time = models.DateTimeField(_('creation time'), default=now)
# 最后修改时间字段:支持国际化标签,默认值为当前时间,记录用户信息最后更新时间
last_modify_time = models.DateTimeField(_('last modify time'), default=now)
# 创建来源字段支持国际化标签最大长度100允许空值用于标记用户注册渠道如"adminsite"/"frontend"/"oauth"
source = models.CharField(_('create source'), max_length=100, blank=True)
def get_absolute_url(self):
"""
重写Django模型的`get_absolute_url`方法获取用户的绝对路径URL
关联博客系统的"作者详情页"路由,用于直接访问用户的个人主页
"""
return reverse(
'blog:author_detail', # 路由名称对应blog应用的作者详情页路由
kwargs={'author_name': self.username} # 路由参数:用户名(作为作者标识)
)
def __str__(self):
"""
重写模型的字符串表示方法,返回用户邮箱作为标识
相比默认的用户名,邮箱更具唯一性,便于后台管理和日志输出时识别用户
"""
return self.email
def get_full_url(self):
"""
扩展方法获取用户个人主页的完整URL包含站点域名
用于需要分享用户主页的场景(如邮件通知、第三方分享)
"""
site = get_current_site().domain # 通过公共工具函数获取当前站点的域名(如"example.com"
# 拼接域名和用户绝对路径生成完整URL支持HTTPS协议
url = "https://{site}{path}".format(site=site, path=self.get_absolute_url())
return url
class Meta:
ordering = ['-id'] # 数据查询时默认按ID倒序排列新注册用户优先展示
verbose_name = _('user') # 模型单数显示名称(支持国际化)
verbose_name_plural = verbose_name # 模型复数显示名称(与单数一致,简化管理)
get_latest_by = 'id' # 按ID字段获取最新创建的用户记录