DEV Community

loading...
Cover image for Follow/Unfollow System using Django || Simple Code ||

Follow/Unfollow System using Django || Simple Code ||

madhubankhatri profile image Madhuban Khatri ・3 min read

Do you use Social Media like Instagram, Twitter, Facebook or Dev. The common thing is all of have Follow/Unfollow System.
Here In this post, You can create your own follow/unfollow system using Python Django. It is very simple to make.

First of all you have to create a Project and App. And here is my Code:-

models.py

from django.db import models

# Create your models here.
class User(models.Model):
    name = models.CharField(max_length=40)
    pwd = models.CharField(max_length=40)

    def __str__(self):
        return self.name


class Followers(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    another_user = models.ManyToManyField(User, related_name='another_user')

    def __str__(self):
        return self.user.name

Enter fullscreen mode Exit fullscreen mode

admin.py

from django.contrib import admin
from .models import User, Followers

# Register your models here.
admin.site.register(User)
admin.site.register(Followers)
Enter fullscreen mode Exit fullscreen mode

app1 - urls.py

from django.urls import path
from . import views
urlpatterns = [
    path('', views.index, name='index'),
    path('profile/<str:user_name>', views.profile, name='profile'),
    path('login/', views.login_user, name='login'),
    path('logout/', views.logout_user, name='logout'),
    path('follow/<str:user_name>', views.follow_user, name='follow'),
]
Enter fullscreen mode Exit fullscreen mode

views.py

from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import User, Followers
# Create your views here.
def index(request):
    if 'user' in request.session:
        return render(request, 'index.html')
    else:
        return redirect('login')



def profile(request, user_name):
    user_obj = User.objects.get(name=user_name)
    session_user = User.objects.get(name=request.session['user'])
        session_following, create = Followers.objects.get_or_create(user=session_user)
    following, create = Followers.objects.get_or_create(user=session_user.id)
    check_user_followers = Followers.objects.filter(another_user=user_obj)

    is_followed = False
    if session_following.another_user.filter(name=user_name).exists() or following.another_user.filter(name=user_name).exists():
        is_followed=True
    else:
        is_followed=False
    param = {'user_obj': user_obj,'followers':check_user_followers, 'following': following,'is_followed':is_followed}
    if 'user' in request.session:
        return render(request, 'profile.html', param)
    else:
        return redirect('index')


def follow_user(request, user_name):
    other_user = User.objects.get(name=user_name)
    session_user = request.session['user']
    get_user = User.objects.get(name=session_user)
    check_follower = Followers.objects.get(user=get_user.id)
    is_followed = False
    if other_user.name != session_user:
        if check_follower.another_user.filter(name=other_user).exists():
            add_usr = Followers.objects.get(user=get_user)
            add_usr.another_user.remove(other_user)
            is_followed = False
            return redirect(f'/profile/{session_user}')
        else:
            add_usr = Followers.objects.get(user=get_user)
            add_usr.another_user.add(other_user)
            is_followed = True
            return redirect(f'/profile/{session_user}')

        return redirect(f'/profile/{session_user}')
    else:
        return redirect(f'/profile/{session_user}')


def login_user(request):
    if request.method == 'POST':
        name = request.POST.get('uname')
        password = request.POST.get('pwd')

        check_user = User.objects.filter(name=name, pwd=password)
        if check_user:
            request.session['user'] = check_user.first().name
            return redirect('index')
        else:
            return redirect('index')
    return render(request, 'login.html')

def logout_user(request):
    del request.session['user']
    return redirect('index')
Enter fullscreen mode Exit fullscreen mode

Templates Work

index.html

<!DOCTYPE html>
<html>
<head>
    <title>Index Page</title>
</head>
<body>
    Login as: <span>{{request.session.user}}</span>
    <br>
    Go to <a href="{% url 'profile' request.session.user %}">Profile</a>
    <hr>
    <a href="{% url 'logout' %}">Logout</a>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

login.html

<!DOCTYPE html>
<html>
<head>
    <title>Login page</title>
</head>
<body>
    <form action="{% url 'login' %}" method="post">
        {% csrf_token %}
        <input type="text" name="uname" placeholder="Name">
        <input type="text" name="pwd" placeholder="Password">
        <input type="submit" value="Login">

    </form>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

profile.html

<!DOCTYPE html>
<html>
<head>
    <title>Profile Page</title>
</head>
<body>
    <h1>Profile Page</h1>
    <hr>
    {% if user_obj.name == request.session.user%}
    <h4>Name: {{user_obj.name}}</h4>
    <span>Followers: {{followers.count }}</span>
    <br>
    <span>Following: {{session_following.another_user.count }}</span>
    {% else %}
    <h4>Name: {{user_obj.name}}</h4>
    <span>Followers: {{followers.count }}</span>
    <br>
    <span>Following: {{user_following.another_user.count }}</span>
    <h4>Profile is Private.</h4>
    {% endif %}
    <br><br>

    {% if user_obj.name != request.session.user%}
    {% if is_followed %}
        <a href="{% url 'follow' user_obj.name %}" style="border: 1px solid; background: red; padding:10px; color: white;">Unfollow</a>
    {% else %}
        <a href="{% url 'follow' user_obj.name %}" style="border: 1px solid; background: yellow; padding:10px; color: black;">Follow</a>
    {% endif %}

    {% endif %}
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

That's it.
Is it simple or not?
Comment below.

Discussion (1)

pic
Editor guide
Collapse
segestic profile image
segestic

Nice one! Keep it up!