import hashlib import datetime from django.db import models from django.contrib.auth.models import User # 引入内置信号 from django.db.models.signals import post_save # 引入信号接收器的装饰器 from django.dispatch import receiver # 用户信息 class Profile(models.Model): # 对应django自带的user user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') # 电话 phone = models.CharField(max_length=20, blank=True) # 个人简介 bio = models.TextField(max_length=500, blank=True) # 头像 avatar = models.ImageField(upload_to='avatar/%Y%m%d/', blank=True) def __str__(self): return 'user {}'.format(self.user.username) # 设备表 class Devices(models.Model): # 对应django自带的User user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='devices') # 设备登录时间 last_login_time = models.DateField(auto_now=True) # 设备码 device_uid = models.CharField(max_length=100, default='233', blank=False, unique=True) # 登录凭证 token = models.CharField(max_length=100, default='233', blank=False, unique=True) def gen_token(self): _token = self.device_uid + self.user.username + datetime.datetime.now().strftime("%Y%m%d%H%M%S") sha1 = hashlib.sha1() sha1.update(_token.encode()) self.token = sha1.hexdigest() # 信号接收函数,每当新建User实例的时候自动调用 @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) # 信号接收函数,每当更新User实例的时候自动调用 @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save()