Published: Dec. 29, 2020 by lukemakin |  estimated reading time: 12 minutes
How to build referral links in django
Source code to the youtube tutorial: How to build referral links using Django | recommendation system Django

Part 1 - https://www.youtube.com/watch?v=QZfflGvRQrc

Part 2 - https://www.youtube.com/watch?v=LH8MiPkOMoo



Learn how to build ref links in a django project (recommend users to your site)



Base.html

<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">

<title>Ref link proj | {% block title %}{% endblock title %}</title>
</head>
<body>
<div class="container mt-3">
{% block content %}
{% endblock content %}
</div>
</body>
</html>

profiles / models.py


from django.db import models
from django.contrib.auth.models import User
from .utils import generate_ref_code
# Create your models here.

class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField(blank=True)
code = models.CharField(max_length=12, blank=True)
recommended_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)

def __str__(self):
return f"{self.user.username}-{self.code}"

def get_recommened_profiles(self):
qs = Profile.objects.all()
# my_recs = [p for p in qs if p.recommended_by == self.user]

my_recs = []
for profile in qs:
if profile.recommended_by == self.user:
my_recs.append(profile)
return my_recs

def save(self, *args, **kwargs):
if self.code == "":
code = generate_ref_code()
self.code = code
super().save(*args, **kwargs)

views.py


from django.shortcuts import render, redirect
from profiles.models import Profile
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import login, authenticate
from django.contrib.auth.models import User

def signup_view(request):
profile_id = request.session.get('ref_profile')
print('profile_id', profile_id)
form = UserCreationForm(request.POST or None)
if form.is_valid():
if profile_id is not None:
recommended_by_profile = Profile.objects.get(id=profile_id)

instance = form.save()
registered_user = User.objects.get(id=instance.id)
registered_profile = Profile.objects.get(user=registered_user)
registered_profile.recommended_by = recommended_by_profile.user
registered_profile.save()
else:
form.save()
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=password)
login(request, user)
return redirect('main-view')
context = {'form':form}
return render(request, 'signup.html', context)

def main_view(request, *args, **kwargs):
code = str(kwargs.get('ref_code'))
try:
profile = Profile.objects.get(code=code)
request.session['ref_profile'] = profile.id
print('id', profile.id)
except:
pass
print(request.session.get_expiry_age())
return render(request, 'main.html', {})

profiles/views.py


from django.shortcuts import render
from .models import Profile
# Create your views here.

def my_recommendations_view(request):
profile = Profile.objects.get(user=request.user)
my_recs = profile.get_recommened_profiles()
context = {'my_recs': my_recs}
return render(request, 'profiles/main.html', context)

urls.py


from django.contrib import admin
from django.urls import path
from .views import main_view, signup_view
from profiles.views import my_recommendations_view

urlpatterns = [
path('admin/', admin.site.urls),
path('', main_view, name='main-view'),
path('signup/', signup_view, name='signup-view'),
path('profiles/', my_recommendations_view, name='my-recs-view'),
path('<str:ref_code>/', main_view, name='main-view'),
]

main.html


{% extends "base.html" %}

{% block title %}
home
{% endblock title %}

{% block content %}

{% if request.user.is_authenticated %}
{{request.user}}
{% else %}
<a href="{% url 'signup-view' %}">
<button class="btn btn-primary">Create an account</button>
</a>
{% endif %}

{% endblock content %}

signup.html


{% extends "base.html" %}
{% load crispy_forms_tags %}

{% block title %}
signup
{% endblock title %}

{% block content %}
<form action="" method="POST">
{% csrf_token %}
{{form|crispy}}
<button type="submit" class="btn btn-primary">Signup</button>
</form>
{% endblock content %}

profiles/main.html


{% extends "base.html" %}

{% block title %}
my recs
{% endblock title %}

{% block content %}
{% if my_recs %}
<h1>My recommendations:</h1>
<ul>
{% for p in my_recs %}
<li>{{p.user}}</li>
{% endfor %}
</ul>
{% else %}
<h1>You didn't recommend anyone yet...</h1>
{% endif %}
{% endblock content %}

profiles/signals.py


from .models import Profile
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=User)
def post_save_create_profile(sender, instance, created, *args, **kwargs):
if created:
Profile.objects.create(user=instance)

profiles/apps.py


from django.apps import AppConfig

class ProfilesConfig(AppConfig):
name = 'profiles'

def ready(self):
import profiles.signals

profiles/ __init__.py


default_app_config = 'profiles.apps.ProfilesConfig'

Extras
To view additional content login or create a free account
Categories:
Share your thoughts

No comments yet...

Signup to the newsletter
To get the latest updates from pyplane
© copyright 2019 pyplane.com