我想在我的系统中实现一个推荐系统,注册用户可以通过电子邮件发送他们的推荐链接(即/ register / referral / 123123 /)来邀请其他人,就像dropbox一样(如果有人注册,推荐者会得到额外奖金。 目前我已经这样实现了它: 机型:
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
因此,每次生成新邀请时,我都会创建虚拟无效'referrer'用户帐户。在注册时,我从用户输入表单填充名称,密码等,并将UserReferral实例状态更改为ACTIVATED。有没有更好的替代品?提前谢谢。