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.
Django/doc/accounts/models.py

64 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.

# 导入Django内置的抽象用户模型用于扩展自定义用户功能包含基础用户名、密码等字段
from django.contrib.auth.models import AbstractUser
# 导入Django模型相关类用于定义数据库表结构
from django.db import models
# 导入reverse函数用于通过URL名称生成对应的URL路径
from django.urls import reverse
# 导入now函数用于获取当前时区的时间作为字段默认值
from django.utils.timezone import now
# 导入翻译工具,用于实现模型字段名称的国际化
from django.utils.translation import gettext_lazy as _
# 导入自定义工具函数get_current_site用于获取当前站点的域名信息
from djangoblog.utils import get_current_site
class BlogUser(AbstractUser):
"""
自定义用户模型继承自Django的AbstractUser
扩展了内置用户模型,增加了昵称、创建时间、修改时间、创建来源等自定义字段
"""
# 昵称字段支持国际化标签最大长度100允许空白不强制填写
nickname = models.CharField(_('nick name'), max_length=100, blank=True)
# 创建时间字段支持国际化标签默认值为当前时间调用now函数
creation_time = models.DateTimeField(_('creation time'), default=now)
# 最后修改时间字段:支持国际化标签,默认值为当前时间
last_modify_time = models.DateTimeField(_('last modify time'), default=now)
# 创建来源字段记录用户创建的渠道如adminsite、frontend等支持国际化标签允许空白
source = models.CharField(_('create source'), max_length=100, blank=True)
def get_absolute_url(self):
"""
定义模型实例的绝对URL标准Django方法
通过URL名称'blog:author_detail'生成用户详情页的URL参数为用户名
"""
return reverse(
'blog:author_detail', kwargs={
'author_name': self.username}) # kwargs传递URL所需的用户名参数
def __str__(self):
"""
定义模型实例的字符串表示
当打印或引用用户实例时,返回用户的邮箱地址(便于识别)
"""
return self.email
def get_full_url(self):
"""
生成用户详情页的完整URL包含站点域名
结合当前站点域名和get_absolute_url生成的相对路径组成完整链接
"""
# 获取当前站点的域名如www.example.com
site = get_current_site().domain
# 拼接域名和相对路径形成完整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判断ID最大的为最新