derekzyl
Posted on September 24, 2021
with current tech of referral being a strategy to boost businesses both offline and online I've chosen to write some codes on how to create referral links with Django-allauth and django sessions.
inspiration of the referral was gotten from a youtube video of pyplane .
import uuid
def generate_ref_code():
code =str(uuid.uuid4()).replace('-', '')[:12]
return code
models
from django.db import models
# Create your models here.
from core.models import TheMain
from referral.utils import generate_ref_code
from user.models import User
class Referral(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
referral_balance = models.IntegerField(default=0)
code = models.CharField(max_length=12, blank=True)
referred_by = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, related_name="ref_by")
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
approve= models.BooleanField(default=False)
def __str__(self):
return f'{self.user.username}- {self.code}'
def get_reffered(self):
qs = Referral.objects.all()
my_refs = []
for reffered in qs:
if reffered.referred_by == self.user:
my_refs.append(reffered)
return my_refs
def save(self, *args, **kwargs):
if self.code == '':
code = generate_ref_code()
self.code = code
super().save(*args, **kwargs)
the user referral id is automatically generated with UUID
the extended all-auth form view I guess I don't need to tell you about djangoallauth.
class mySignUp(SignupForm):
first_name = forms.CharField(max_length=50, widget=forms.TextInput(attrs={
'placeholder': 'First name'
}))
last_name = forms.CharField(max_length=50, widget=forms.TextInput(attrs={
'placeholder': 'Last name'
}))
country = CountryField(blank_label='select country').formfield(widget=CountrySelectWidget(attrs={
'class': 'custom-select d-block w-100'
}))
phone = forms.IntegerField(required=True, widget=forms.TextInput(attrs={
'placeholder': 'Phone number'
}))
# def save(self, request):
# user = super(mySignUp, self).save(request)
#
# user.first_name = self.cleaned_data['first_name']
# user.last_name = self.cleaned_data['last_name']
# user.country = self.cleaned_data['country']
# user.phone = self.cleaned_data['phone']
# user.save()
# print(f'this is the user {user}')
# return user
def save(self, request):
referral_id = request.session.get('ref_profile')
print(f'this is login{referral_id}')
if referral_id is not None:
recommended_by_profile = Referral.objects.get(id=referral_id)
user = super(mySignUp, self).save(request)
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.country = self.cleaned_data['country']
user.phone = self.cleaned_data['phone']
user.save()
registered_user = User.objects.get(id=user.id)
registered_profile = Referral.objects.get(user=registered_user)
registered_profile.referred_by = recommended_by_profile.user
registered_profile.save()
print(f'this is the user {user}')
print(f'this is the the {user.id}')
# here after saving the registration I pass the ref id param to the user profile then I save the user
profile
return user
else:
user = super(mySignUp, self).save(request)
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.country = self.cleaned_data['country']
user.phone = self.cleaned_data['phone']
user.save()
print(f'this is the user {user}')
return user
def referred(request, *args, **kwargs):
code = str(kwargs.get('ref_code'))
print(f'coded code {code}')
try:
referral = Referral.objects.get(code=code)
request.session['ref_profile'] = referral.id
print('id', referral.id)
except:
pass
print(request.session.get_expiry_age())
return render(request, 'homepage/index.html', {})
# now in my views I fetch the referred users
from allauth.account.views import SignupView
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.shortcuts import render, get_object_or_404
# Create your views here.
from core.models import TheMain, Invest, TheRef
from referral.models import Referral
@login_required
def referral_page(request, *args, **kwargs):
global invest_user, invest_name, invest_amount, invest_timer, main, that, ma, new_invest, new_main
referral = get_object_or_404(Referral, user=request.user)
my_ref = referral.get_reffered()
contact me if you need more explanation to this
reference
https://www.youtube.com/watch?v=QZfflGvRQrc
by pyplane
π πͺ π
π©
derekzyl
Posted on September 24, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.