将默认组分配给新用户Django [英] Assign default group to new user Django

查看:99
本文介绍了将默认组分配给新用户Django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为注册到系统中的每个新用户分配一个组。我已经在另一个问题中阅读了有关它的内容,但我真的不知道在哪里添加必要的代码以使其正常工作。

我正在使用Django 2.1.3,并且正在记录用户使用allauth(社交登录,但在创建User表中的新实例时不会有任何区别)

I'm trying to assign a group to every new user registered into the system. I've already read something about it in another questions but I don't really know where to add the necessary code to make it work.
I'm using Django 2.1.3 and I'm logging users using allauth (social login, but it shouldn't make any difference as a new instance in the User table is created)

推荐答案

例如,您可以使用 @post_save 信号,每次创建 User 时,都会将给定的组添加到用户的用户组。通常,信号驻留在 app < signals 目录中的 handlers.py 文件中。 / code>,因此您可能应该创建或修改以黑体字列出的文件:

You can use a @post_save signal for example that, each time a User is created, adds the given group to the groups of the User. Typically signals reside in a file named handlers.py in the signals directory of an app, so you probably should create or modify the files listed in boldface:

app/
    signals/
        __init__.py
        handlers.py
    __init__.py
    apps.py
    ...



# app/signals/handlers.py

from django.db.models.signals import post_save
from django.dispatch import receiver
from django.conf import settings
from django.contrib.auth.models import Group

@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def save_profile(sender, instance, created, **kwargs):
    if created:
        g1 = Group.objects.get(name='group_name')
        instance.groups.add(g1)

其中 group_name 是要添加的组的名称。

where group_name is the name of the group you want to add.

你应该d然后在 MyAppConfig 中导入 handlers.py 模块(如果尚未构建这样的配置,则创建一个) :

You should then import the handlers.py module in your MyAppConfig (create one if you do not have constructed such config yet):

# app/apps.py

from django.apps import AppConfig

class MyAppConfig(AppConfig):
    name = 'app'
    verbose_name = "My app"

    def ready(self):
        import app.signals.handlers

并在<$ c $中注册 MyAppConfig 应用程序的c> __ init __。py

and register the MyAppConfig in the __init__.py of the app:

# app/__init__.py

default_app_config = 'app.apps.MyAppConfig'

这篇关于将默认组分配给新用户Django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆