Django——User-Profile

Profile作用:User内置的字段不够完善,导致创建的用户信息单一,Profile就是为了对User进行扩展,即丰富用户信息

  • 在models中创建Profile类,添加字段user与User形成OneToOne关系以及级联删除
    on_delete=models.CASCADE

 

  • 引入与信号相关的包
from django.dispatch import receiver
from django.db.models.signals import post_save
  • 装饰器装饰函数,User创建时信号触发自动创建Profile的user字段并关联;User保存时信号触发,Profile自动保存
  • 源码
     1 from django.db import models
     2 from django.contrib.auth.models import User
     3 #信号
     4 from django.db.models.signals import post_save,post_init
     5 from django.dispatch import receiver
     6 
     7 class Profile(models.Model):
     8     user = models.OneToOneField(User,on_delete=models.CASCADE)
     9     birth = models.DateField(null=True,blank=True)
    10 
    11     def __str__(self):
    12         return self.user.username
    13 
    14     class Meta:
    15         db_table = 'profile'
    16 
    17 
    18 @receiver(post_save,sender=User)
    19 def create_user_profile(sender,instance,created,**kwargs):
    20     print('创建User')
    21     if created:
    22         Profile.objects.create(user=instance)
    23 
    24 @receiver(post_save,sender=User)
    25 def save_user_profile(sender,instance,**kwargs):
    26     print('保存User')
    27     instance.profile.save()

     

 

posted @ 2018-09-14 18:53  BO00097  阅读(599)  评论(0编辑  收藏  举报