models.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import hashlib
  2. import datetime
  3. from django.db import models
  4. from django.contrib.auth.models import User
  5. # 引入内置信号
  6. from django.db.models.signals import post_save
  7. # 引入信号接收器的装饰器
  8. from django.dispatch import receiver
  9. # 用户信息
  10. class Profile(models.Model):
  11. # 对应django自带的user
  12. user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
  13. # 电话
  14. phone = models.CharField(max_length=20, blank=True)
  15. # 个人简介
  16. bio = models.TextField(max_length=500, blank=True)
  17. # 头像
  18. avatar = models.ImageField(upload_to='avatar/%Y%m%d/', blank=True)
  19. def __str__(self):
  20. return 'user {}'.format(self.user.username)
  21. # 设备表
  22. class Devices(models.Model):
  23. # 对应django自带的User
  24. user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='devices')
  25. # 设备登录时间
  26. last_login_time = models.DateField(auto_now=True)
  27. # 设备码
  28. device_uid = models.CharField(max_length=100, default='233', blank=False, unique=True)
  29. # 登录凭证
  30. token = models.CharField(max_length=100, default='233', blank=False, unique=True)
  31. def gen_token(self):
  32. _token = self.device_uid + self.user.username + datetime.datetime.now().strftime("%Y%m%d%H%M%S")
  33. sha1 = hashlib.sha1()
  34. sha1.update(_token.encode())
  35. self.token = sha1.hexdigest()
  36. # 信号接收函数,每当新建User实例的时候自动调用
  37. @receiver(post_save, sender=User)
  38. def create_user_profile(sender, instance, created, **kwargs):
  39. if created:
  40. Profile.objects.create(user=instance)
  41. # 信号接收函数,每当更新User实例的时候自动调用
  42. @receiver(post_save, sender=User)
  43. def save_user_profile(sender, instance, **kwargs):
  44. instance.profile.save()