models.py 1.1 KB

123456789101112131415161718192021222324252627282930313233
  1. from django.db import models
  2. from django.contrib.auth.models import User
  3. # 引入内置信号
  4. from django.db.models.signals import post_save
  5. # 引入信号接收器的装饰器
  6. from django.dispatch import receiver
  7. # 用户拓展信息
  8. class Profile(models.Model):
  9. # 与User模型构成一对一关系
  10. user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
  11. phone = models.CharField(max_length=20, blank=True)
  12. # 头像
  13. avatar = models.ImageField(upload_to='avatar/%Y%m%d/', blank=True)
  14. # 个人简介
  15. bio = models.TextField(max_length=500, blank=True)
  16. def __str__(self):
  17. return 'user {}'.format(self.user.username)
  18. # 信号接收函数,每当新建User实例的时候自动调用
  19. @receiver(post_save, sender=User)
  20. def create_user_profile(sender, instance, created, **kwargs):
  21. if created:
  22. Profile.objects.create(user=instance)
  23. # 信号接收函数,每当更新User实例的时候自动调用
  24. @receiver(post_save, sender=User)
  25. def save_user_profile(sender, instance, **kwargs):
  26. instance.profile.save()