我正在使用Django,django-allauth和django-invitations。我能够成功邀请用户加入平台,但我想将他们与邀请人的公司相关联。
我已经阅读了养蜂人/姜戈邀请,它似乎没有关于如何做到这一点的信息。
models.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()
views.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中实现一个信号。它侦听用户注册,然后查看该用户是否在邀请模型中。如果是这样,它会查找邀请者的公司,并将其与注册的用户相关联。
初始化.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()