我正在使用Django,django-allauth和django-invitations。我能够成功邀请用户使用该平台,但是我想将他们与邀请者的公司相关联。
我已阅读了养蜂人/ django的邀请函,似乎没有有关如何执行此操作的信息。
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()
@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,
})
在上面的代码中,已成功将用户邀请到平台,但该用户未与邀请者的公司关联。我还担心受邀请用户的列表不仅限于该用户的公司。
答案 0 :(得分:0)
我不得不在Django中实现Signal。它侦听用户注册,然后查看该用户是否在邀请模型中。如果是这样,它将查找邀请者的公司,并将其与注册用户相关联。
初始化 .py
default_app_config = "users.apps.UsersConfig"
signals.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()