1

我想在我的系统中实现一个推荐系统,注册用户可以通过电子邮件发送他们的推荐链接(即/register/referral/123123/)来邀请其他人,就像保管箱一一样(如果有人注册,推荐人会获得额外的奖金。目前我已经以这种方式实现了它:模型:

class UserReferral(models.Model):
STATUS_INVITED = 1
STATUS_ACCEPTED = 2
STATUS_EXPIRED = 3

STATUS_CHOICES = (
    (STATUS_INVITED, 'Invited'),
    (STATUS_ACCEPTED, 'Accepted'),
    (STATUS_EXPIRED, 'Expired'),
    )

referrer = models.ForeignKey(User, related_name='referrers')
referred = models.ForeignKey(User, related_name='referred')
number = models.IntegerField()
status = models.IntegerField(choices=STATUS_CHOICES, default=STATUS_INVITED)

class Meta:
    unique_together = (('referrer', 'referred'),)

def __unicode__(self):
    return 'User %s referred %s' % (self.referrer.get_full_name(), self.referred.get_full_name())

@property
def referral_expired(self):
    expiration_date = datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS)
    return (self.status == self.STATUS_ACCEPTED or
                   (self.referred.date_joined + expiration_date <= datetime_now()))

视图:注册用户使用此视图发送新的推荐邀请

@login_required
def invite_friends(request, template_name='accounts/invite_friends.html'):
if request.method == 'POST':
    form = InviteForm(request.POST, user=request.user)
    if form.is_valid():
        emails = form.cleaned_data['emails']
        for email in emails:
            try:
                user_referral = UserReferral.objects.get(referrer=request.user, referred__email=email)
            except UserReferral.DoesNotExist:
                random_username = ''.join(random.choice(string.ascii_uppercase) for x in range(6))
                user = User.objects.create(username=random_username, password=email, is_active=False)  # Dummy user to be overridden
                user_referral = UserReferral.objects.create(referrer=request.user, referred=user, number=random.randint(10000, 99999))
                send_mail('accounts/notifications/invite_friends', recipient_list=[email],
                        context={'user': request.user, 'number': user_referral.number})

        messages.add_message(request, messages.SUCCESS, "Invites are sent.")
        return redirect(reverse('profile_dashboard'))
else:
    form = InviteForm(user=request.user)
return render(request, template_name, locals())

这是被推荐用户可以注册的 URL,它基本上使用推荐代码调用原始注册函数,并在注册视图中检查推荐代码是否存在,如果存在,它会从 UserReferral 实例中获取被推荐的用户实例并填充注册表格中的用户数据并保存该新用户。

def referred_signup(request, referral_code):
user_referral = get_object_or_404(UserReferral, number=referral_code)
if user_referral.referral_expired:
    raise Http404
response = register(request, referral_code=referral_code)
return response

因此,每次生成新邀请时,我都会创建一个虚拟的非活动“推荐人”用户帐户。在注册时,我从用户输入表单中填充名称、密码等,并将 UserReferral 实例状态更改为 ACTIVATED。有没有比这个更好的选择?

4

0 回答 0