自動一個
User class
python manager startapp user
繼承
user class
可以自行擴展# vim user.models from django.contrib.auth.models import AbstractUser #Createyourmodelshere. classUser(AbstractUser): pass
建立
signals.py
# vim user.signals from django.dispatch import receiver from django.db.models.signals import post_save from django.conf import settings from django.contrib.auth.models import Group @receiver(post_save, sender=settings.AUTH_USER_MODEL) def auto_grant_group(sender, **kwargs): user = kwargs['instance'] if kwargs["created"]: if not user.is_superuser: user.is_staff = True try: g = Group.objects.get(name='view_only') g.user_set.add(user) except Group.DoesNotExist: # print info print("group 不存在") user.save()
註冊 signals
# vim user.apps from django.apps import AppConfig from django.db.models.signals import post_save from django.conf import settings class UserConfig(AppConfig): name = 'user' def ready(self): # signals are imported, so that they are defined and can be used from user.signals import auto_grant_group
在 settings 註冊新的 user class
# vim settings INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'user.apps.UserConfig', ] AUTH_USER_MODEL = 'user.User'