前言
在第一篇文件分享了登录页的开发。在用户登录之前,需要注册。注册时,除了系统默认的user表。还有自动创建扩展信息条目。用到了Django的信号机制。
过程
修改apps.py,然后项目目录下创建signals.py文件,接收到信号处理。
apps.py
from django.apps import AppConfig
class UsersConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'users'
def ready(self):
import users.signals
default_app_config = 'users.UsersConfig'
signals.py
做的操作都可以放到这个函数里。
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils import timezone
from django.contrib.auth.models import User
from .models import UserProfile
from django.contrib.sessions.models import Session
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
"""
后台新增用户时,自动新建扩展信息
"""
if created:
UserProfile.objects.create(owner=instance)
@receiver(post_save, sender=UserProfile)
def handle_user_profile(sender, instance, created, **kwargs):
"""
后台锁定此用户时,踢掉此用户
"""
if instance.status == 2:
sessions = Session.objects.filter(expire_date__gte=timezone.now())
for session in sessions:
session_data = session.get_decoded()
if str(instance.owner.id) == session_data.get('_auth_user_id'):
session.delete()
评论 (0)