DEV Community

Cover image for Follow/Unfollow System using Django || Simple Code ||
Madhuban Khatri
Madhuban Khatri

Posted on • Updated on

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

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.

Top comments (9)

Collapse
 
bphariharan1301 profile image
HARIHARAN B P

Can you explain what the code does? Because, its easy to read from screenshots but, it's you who knows what the code does, Maybe you can make a video on your YT channel and publish it so that we can also understand, the logic is pretty simple but, some part of code went like bouncer, So, if you can explain it in this post itself is well and good.
Thank you.

Collapse
 
cpoonam47 profile image
cpoonam47

Itna sikhte kaha se Dost

Collapse
 
cpoonam47 profile image
cpoonam47

Itna sikhte kaha se Dost

Collapse
 
madhubankhatri profile image
Madhuban Khatri

YouTube or Google

Collapse
 
cpoonam47 profile image
cpoonam47

upload, show, and download image and video par code link send kariyega because your method is the best.

Collapse
 
segestic profile image
segestic

Nice one! Keep it up!

Collapse
 
ruturajsingare profile image
RuturajSingare

Wow ! Its really simple Dude.

Collapse
 
amarr profile image
Amaar305

Wow, that's so amazing đź‘Ź but the thing is; I couldn't fetch following count for non session_user, pls help me with that.

Some comments may only be visible to logged-in visitors. Sign in to view all comments. Some comments have been hidden by the post's author - find out more