Step-by-Step Guide to Implement Follow/Unfollow Functionality in Django

Aug. 13, 2023


0
3 min read
1.67K

Django, a robust web framework, empowers developers to create dynamic and sophisticated web applications with ease. If you're looking to enhance your Django application with a follow/unfollow feature, you're in the right place. This guide will walk you through the process step by step, enabling you to implement this social networking functionality seamlessly.

Introduction to Follow/Unfollow Functionality

In today's interconnected digital landscape, social interactions are a cornerstone of many web applications. Incorporating a follow/unfollow feature allows users to subscribe to updates from other users, fostering engagement and community-building. Whether you're building a blogging platform, a social network, or any app that thrives on user interactions, implementing follow/unfollow functionality can elevate your user experience.

Step 1: User Model

Make sure you have a custom User model or extend the built-in User model to include the necessary fields for the follow functionality. You might need to install a package like django.contrib.auth to handle user authentication.

Step 2: Create the Follow Model

Create a model to represent the relationship between users. The Follow model will store information about who is following whom. Here's an example model:

from django.db import models
from django.contrib.auth import get_user_model

User = get_user_model()

class Follow(models.Model):
    follower = models.ForeignKey(User, related_name='following', on_delete=models.CASCADE)
    following = models.ForeignKey(User, related_name='followers', on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)

In this model, follower and following are foreign keys to the User model, representing the user who follows and the user who is being followed, respectively? The created_at field stores the timestamp when the following relationship is created.

Step 3: URLs and Views

Define URLs and views for following and unfollowing users. In the following example, we'll create two views - follow_user and unfollow_user - for following and unfollowing users.

# urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('follow/<int:user_id>/', views.follow_user, name='follow_user'),
    path('unfollow/<int:user_id>/', views.unfollow_user, name='unfollow_user'),
]

# views.py
from django.shortcuts import get_object_or_404, redirect

def follow_user(request, user_id):
    user_to_follow = get_object_or_404(User, id=user_id)
    if not request.user.following.filter(id=user_id).exists():
        Follow.objects.create(follower=request.user, following=user_to_follow)
    return redirect('profile_page')

def unfollow_user(request, user_id):
    user_to_unfollow = get_object_or_404(User, id=user_id)
    request.user.following.filter(id=user_id).delete()
    return redirect('profile_page')

In the URLs, we use <int:user_id> to capture the user ID of the user to follow or unfollow. In the views, we fetch the corresponding user based on the provided ID and create or delete the follow relationship.

Step 4: Templates

Create buttons or links in your templates to call the follow/unfollow views using appropriate user IDs. For example:

{% if not request.user == user_to_follow %}
    {% if request.user.following.filter(id=user_to_follow.id).exists %}
        <a href="{% url 'unfollow_user' user_to_follow.id %}">Unfollow</a>
    {% else %}
        <a href="{% url 'follow_user' user_to_follow.id %}">Follow</a>
    {% endif %}
{% endif %}

In this example, we check if the current user is not the same as the user to follow. If true, we check if there is a follow relationship between the current user and the user to follow. Depending on the result, we display a "Follow" or "Unfollow" link.

Step 5: Protect Views

Ensure that only authenticated users can access the follow/unfollow views using the @login_required decorator or equivalent. This prevents unauthorized access and ensures that only logged-in users can follow or unfollow others.

With these steps, you now have a basic follow/unfollow functionality in your Django app. Customize it further based on your specific application requirements. You can expand the feature to include notifications, friend suggestions, or any other social networking features you desire.

django views Unfollow Follow Appreciate you stopping by my post! 😊

Add a comment


Note: If you use these tags, write your text inside the HTML tag.
Login Required