django - 如何将受邀用户关联到邀请人的公司/群组?

标签 django django-allauth

我正在使用 Django、django-allauth 和 django-invitations。我能够成功邀请用户加入平台,但我想将他们与邀请人的公司相关联。

我已经阅读了 bee-keeper/django-invitations,它似乎没有关于如何执行此操作的信息。

模型.py

class Company(models.Model):
    name = models.CharField(max_length=100, default=None)

class CustomUser(AbstractUser):
    company = models.ForeignKey(Company, on_delete=models.CASCADE, blank=True, null=True)
    objects = CustomUserManager()

View .py

@login_required
def company_users(request):
    # Get users that are in the company's user database as well as users that have been invited
    company_users = CustomUser.objects.filter(company=request.user.company.id)
    Invitations = get_invitation_model()
    # I'm afraid this is going to get all invited users, not just those that belong to the company
    invited_users = Invitations.objects.filter()

    if request.method == 'POST':
        print(request.POST)
        invitees = request.POST['invitees']
        invitees = re.split(',', invitees)
        for invitee in invitees:
            Invitation = get_invitation_model()
            try:
                invite = Invitation.create(invitee, inviter=request.user)
                invite.send_invitation(request)
            except IntegrityError as e:
                print(type(e))
                print(dir(e))
                return render(request, "company_users.html", {
                    'message': e.args,
                    'company_users' : company_users,
                    'invited_users' : invited_users,
                    })

    
    return render(request, 'company_users.html', {
        'company_users' : company_users,
        'invited_users' : invited_users,
    })

在上面的代码中,用户被成功邀请到平台,但用户与邀请人的公司没有关联。我也担心受邀用户的列表不限于用户的公司。

最佳答案

我必须在 Django 中实现一个 Signal。它监听注册的用户,然后查看该用户是否在邀请模型中。如果是这样,它会查找邀请者的公司并将其与注册用户相关联。

初始化.py

default_app_config = "users.apps.UsersConfig"

信号.py

from allauth.account.signals import user_signed_up
from django.dispatch import receiver

from invitations.utils import get_invitation_model

@receiver(user_signed_up)
def user_signed_up(request, user, **kwargs):
    try:
        Invitation = get_invitation_model()
        invite = Invitation.objects.get(email=user.email)
    except Invitation.DoesNotExist:
        print("this was probably not an invited user.")
    else:
        user.company = invite.inviter.company
        user.save()

关于django - 如何将受邀用户关联到邀请人的公司/群组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57207796/

相关文章:

python - 使用 django-allauth 保存自定义用户模型

Django 配置文件显示完成百分比

python - 运行测试时找不到 Django 中已安装的应用程序

html - Django Allauth - 如何将自定义 css 类添加到字段?

nginx - Facebook oauth 身份验证重定向到本地主机而不是我的域

python - 覆盖rest-auth注册以向我的后端添加额外的字段

python - 从 django 数据库加载图像文件路径时出错

django - 我无法登录管理员,并且在自定义用户后登录在 Django 项目中不起作用

python / celery : how can I kill subtasks when killing a parent task?

当检索到的电子邮件与现有用户的电子邮件匹配时,django allauth facebook 重定向到注册?