Django has implemented a follow function that is almost essential for SNS apps. It will be a self-implementation that does not use the library. Customize it to suit your needs and requirements.
--You can follow / unfollow --You can't follow yourself --You can check the number of followers and followers
The list of followers is omitted here. Implement the minimum required functional requirements.
There is a way to create only one table, but I personally have the impression that the SQL statement becomes redundant and it is difficult to manage the table, so I will prepare two this time.
** follow_relation table **
data | Information to store | Data type |
---|---|---|
user_id | User ID of the follower | UUID |
followed_id | User ID of the person being followed | UUID |
** follow_count table **
data | Information to store | data型 |
---|---|---|
user_id | User ID | UUID |
follow | Number of followers | INT |
followed | Number being followed | INT |
The follow_relation
table manages the follow status between users, and the follow_count
table manages the number of followers and followers of users.
Let's implement the follow function as soon as the table is created. The general flow of the follow function is as follows.
Page request
↓
followd_Check & display follow status with status function
↓
Press the follow button
↓
The follows function processes according to the follow status
↓
Redirect to original page
Then it becomes the following code.
followed_status function
@login_required
def followed_status(request, accesskey):
#abridgement
#Get the parameters you need
#Connect to database
connection = MySQLdb.connect(
host='localhost',
user='***',
passwd='***',
db='***',
charset="utf8"
)
#Get cursor
cursor = connection.cursor()
#Set of queries
follow_relation = "SELECT COUNT(*) FROM follow_relation where user_id = UUID_TO_BIN(%s) and followed_id = UUID_TO_BIN(%s);"
#Executing a query
# user_id、followed_Get id by yourself
cursor.execute(follow_relation, (user_id, followed_id))
row_follow = cursor.fetchone()
follows = row_follow[0]
#Determine if the login user and page user are the same person
#Make sure you can't follow the same person
if followed_id == user_id:
followed_status_code = 1
else:
followed_status_code = 2
#True if follows is greater than 0
#Returns False if follows is 0
followed = False
if follows > 0 :
followed = True
return followed_status_code, followed
Please pull out the required parameters from your own table.
All you need this time is the ID of the follower and the follower.
The side that user_id
follows and the side that followed_id
follows.
--Match user IDs
Assign a status code to determine if they are the same person.
If followed_status_code = 1
, then yourself (cannot follow)
If followed_status_code = 2
, others (you can follow)
Will be.
--Check the follow status
Check the follow status with True and False.
If it's False
, I haven't followed it yet
If True
, you are already following
Will be. Now let's look at the follows function.
follows function
@login_required
def followes(request, accesskey):
#abridgement
#Get the parameters you need
#Connect to database
connection = MySQLdb.connect(
host='localhost',
user='***',
passwd='***',
db='***',
charset="utf8"
)
#Get cursor
cursor = connection.cursor()
#Please set a common query
#Get the information you need here
#Prevent yourself from following
if user_id == followed_id:
followed = False
#Save follow status to session
request.session['page_followed_status'] = followed
else:
if followed == False:
#It will be the process when following
#Set of queries
#Insert new follow relationship
follow_reation = "INSERT INTO follow_relation (user_id, followed_id) values(UUID_TO_BIN(%s), UUID_TO_BIN(%s));"
#Increase the number of followers by one
follow_update = "UPDATE follow_count SET follow = follow + 1 where user_id=UUID_TO_BIN(%s);"
#Increase the number of followers of the follower user by one
followed_update = "UPDATE follow_count SET followed = followed + 1 where user_id=UUID_TO_BIN(%s);"
#Executing a query
cursor.execute(follow_relation, (user_id, followed_id))
cursor.execute(follow_update, (user_id, ))
cursor.execute(followed_update, (followed_id, ))
#Close the connection
cursor.close()
connection.commit()
connection.close()
#Make it follow
followed = True
request.session['page_followed_status'] = followed
else:
#It will be the process when unfollowing
#Set of queries
#Delete follow relationship
follow_relation = "DELETE FROM follow_relation where user_id=UUID_TO_BIN(%s) and followed_id = UUID_TO_BIN(%s);"
#Reduce the number of unfollowed users by one
follow_update = "UPDATE follow_count SET follow = follow - 1 where user_id=UUID_TO_BIN(%s);"
#Reduce the number of followers of unfollowed page users by one
followed_update = "UPDATE follow_count SET followed = followed - 1 where user_id=UUID_TO_BIN(%s);"
#Executing a query
cursor.execute(sql_followrelation_delete, (user_id, followed_id))
cursor.execute(sql_follow_update, (user_id, ))
cursor.execute(sql_followed_update, (followed_id, ))
#Close the connection
cursor.close()
connection.commit()
connection.close()
#Make it unfollowed
followed = False
request.session['page_followed_status'] = followed
return redirect('Original page', accesskey)
This is the actual processing of branching with an if statement and following or unfollowing. And finally, the follow status is switched. Redirect to the original page and finish. (This time, page transition occurs because Ajax etc. are not used)
Finally, edit the view for display.
result function
@login_required
def result(request, accesskey):
#abridgement
#Understand the status of follow
status = followed_status(request, accesskey)
followed_status_code = status[0]
followed = status[1]
#Save follow status to session (temporary)
request.session['page_followed_status'] = followed
params = {
#abridgement
'page_followed_status': followed,
'page_followed_status_code': followed_status_code,
}
return render(request, 'result.html', params)
Only the relevant parts are listed.
We are checking the follow status by calling the followed_status
function.
(The followed_status
function returns the status code and follow status.)
And I save it temporarily in the session.
urls.py
urlpatterns = [
#abridgement
path('Original page', views.pages, name='Set by yourself'),
path('Original page/follow/', views.follows, name="follows"),
#abridgement
]
Finally, the template.
result.html
<!--Add follow button-->
{% if page_followed_status_code is 2 %}
{% if page_followed_status is False %}
<p><a href="{% url 'follows' page_accesskey %}">To follow</a></p>
{% else %}
<p><a href="{% url 'follows' page_accesskey %}">Stop following</a></p>
{% endif %}
{% endif %}
It is displayed only when the status code is 2
(when it is between others, not yourself).
And if the follow status is False
, it is displayed as" follow ", and when it is True
, it is displayed as "stop following".
When the link is pressed, the follows function is called at the page destination, the follow process is performed, and the page is redirected to the original page.
Please modify the code and use it in your own way. You can implement the "Like feature" in much the same way!
Recommended Posts