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

73 lines
2.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
# Create your models here.
class BlogUser(AbstractUser):
"""
博客用户模型,继承 Django 的 AbstractUser
添加了博客系统需要的额外字段,如昵称、创建时间、修改时间和来源。
"""
nickname = models.CharField(
_('nick name'), # 字段在 admin 或表单中的显示名称(可翻译)
max_length=100, # 昵称最大长度为 100
blank=True # 可以为空
)
creation_time = models.DateTimeField(
_('creation time'), # 创建时间字段
default=now # 默认值为当前时间
)
last_modify_time = models.DateTimeField(
_('last modify time'), # 最近修改时间
default=now
)
source = models.CharField(
_('create source'), # 用户来源字段,例如“注册、后台添加等”
max_length=100,
blank=True
)
def get_absolute_url(self):
"""
返回用户详情页的 URL用于在模板或视图中直接获取用户个人主页链接。
这里使用 username 作为参数。
"""
return reverse(
'blog:author_detail', kwargs={
'author_name': self.username
}
)
def __str__(self):
"""
返回对象的字符串表示,这里使用 email方便在 admin 或调试时查看。
"""
return self.email
def get_full_url(self):
"""
返回带域名的完整用户详情页 URL。
例如https://example.com/blog/author/username
"""
site = get_current_site().domain # 获取当前站点域名
url = "https://{site}{path}".format(
site=site,
path=self.get_absolute_url()
)
return url
class Meta:
ordering = ['-id'] # 默认按 ID 降序排列
verbose_name = _('user') # 在 admin 中显示的名称
verbose_name_plural = verbose_name # 复数形式
get_latest_by = 'id' # get_latest 方法默认按 ID 获取最新对象