【问题标题】:How to give staff access to newly created User In Django如何让员工访问 Django 中新创建的用户
【发布时间】:2019-03-26 06:20:35
【问题描述】:

我是 Djnago 和 Python 的新手。 我在 Djnago 中创建了名为 StaffAccessMiddleware 的中间件类 我使用 social_django 应用程序从 Gmail 创建用户,我想实现 is_staff = True 并仅在用户首次登录 DJango 时分配至少一个组。

我的问题是如何在中间件中访问用户,并且只检查用户第一次输入此代码的情况,在这种情况下,我需要分配 is_staff = True 并在创建用户后分配组。

我尝试创建如下中间件类。

class StaffAccessMiddleware(object):
    def process_request(self, request):
        if hasattr(request, 'user') and request.user.is_authenticated():
                user = request.user
        if groups:
            groups[0].name
        return None

【问题讨论】:

    标签: django python-2.7 django-models django-rest-framework django-middleware


    【解决方案1】:

    我建议你使用pipeline,像这样:

    1. 添加自定义管道以将用户更新为is_staff=True
    2. 在该管道中检查is_new 参数并仅在is_newTrue 时更新用户。 Social-auth 在用户首次登录时(即创建用户时)发送is_new=True
    3. SOCIAL_AUTH_PIPELINE 设置中添加您的自定义管道。
    4. 然后您可以通过指定permission_required 设置将某些视图限制为员工用户。

    您的最终管道可能如下所示:

    def make_new_user_as_staff(backend, user, is_new=False, *args, **kwargs):
        if backend.name == 'gmail' and is_new:
            user.is_staff = False
            user.save()
    

    settings.py(或设置文件)中

    SOCIAL_AUTH_PIPELINE = (
        #other pipelines goes here
        "<full-path-to-make_new_user_as_staff-pipeline>",
        #some other pipelines goes here
    )
    

    参考:https://python-social-auth-docs.readthedocs.io/en/latest/pipeline.html

    如果我误解了您的查询/这不能解决您的问题,请告诉我

    【讨论】:

      猜你喜欢
      • 2020-07-27
      • 1970-01-01
      • 1970-01-01
      • 2010-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-30
      • 2011-03-30
      相关资源
      最近更新 更多