You are currently viewing 建立帳號自動給權限

建立帳號自動給權限

  1. 自動一個 User class

    python manager startapp user
  2. 繼承 user class 可以自行擴展

    # vim user.models
    
    from django.contrib.auth.models import AbstractUser
    
    #Createyourmodelshere.
    classUser(AbstractUser):
      pass
    
  3. 建立 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()
  4. 註冊 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
    
  5. 在 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'
    

Beck Yeh

熱愛學習於 Linux 與 程式設計 在網站中分享各式各樣學習到的新知識

發佈留言

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料