38 lines
1.6 KiB
Python
38 lines
1.6 KiB
Python
from django.conf.global_settings import MEDIA_ROOT
|
|
from django.db import models
|
|
import os
|
|
|
|
|
|
def user_directory_path(instance, filename):
|
|
ext = filename.split('.').pop()
|
|
filename = '{0}{1}.{2}'.format(instance.username, instance.phone, ext)
|
|
return os.path.join("avatar", filename) # 系统路径分隔符差异,增强代码重用性
|
|
|
|
|
|
# Create your models here.
|
|
class User(models.Model):
|
|
"""
|
|
用户表
|
|
"""
|
|
id = models.AutoField(verbose_name="id", primary_key=True, unique=True)
|
|
username = models.CharField(max_length=50, unique=True, verbose_name="用户名", null=True, blank=True)
|
|
pwd = models.CharField(max_length=1000, verbose_name="密码", null=True, blank=True)
|
|
email = models.EmailField(max_length=100, verbose_name="电子邮件")
|
|
phone = models.CharField(max_length=11, verbose_name="手机", null=True, blank=True)
|
|
create_time = models.DateTimeField(verbose_name="注册时间")
|
|
avatar = models.ImageField(verbose_name="头像", upload_to=user_directory_path)
|
|
last_login_time = models.DateTimeField(verbose_name="最后登录时间", auto_now=True)
|
|
|
|
def __str__(self):
|
|
return self.username
|
|
|
|
class Meta:
|
|
verbose_name = '用户表'
|
|
|
|
# 这里定义一个方法,作用是当用户注册时没有上传照片,模板中调用 [ModelName].[ImageFieldName].url 时赋予一个默认路径
|
|
def avatar_url(self):
|
|
if self.avatar and hasattr(self.avatar, 'url'):
|
|
return self.avatar.url
|
|
else:
|
|
return '/media/avatar/default.jpg'
|