常见signal类型
pre_save 对象save前触发
post_save 对象save后触发
pre_delete 对象delete前触发
post_delete 对象delete后触发
m2m_changed ManyToManyField 字段更新后触发
用户注册案例的使用
signals.py
from django.contrib.auth import get_user_model
from django.db.models.signals import post_save
from django.dispatch import receiver
User = get_user_model()
@receiver(post_save, sender=User)
def create_user_profile(sender, instance = None, created = False, **kwargs):
if created:
password = instance.password
instance.set_password(password)
# User.objects.create(user=instance)
instance.save()
apps.py
from django.apps import AppConfig
class UsersConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'apps.users'
verbose_name = '用户管理'
# 注册信号
def ready(self):
import apps.users.signals
备注
在用户注册之前,加密了 password, 相当于重写create方法
0则评论给“django使用signal”