create account

Make social media applications with Flask #12: List user followers and following, Set Limit of data in feeds by duski.harahap

View this thread on: hive.blogpeakd.comecency.com
· @duski.harahap ·
$23.82
Make social media applications with Flask #12: List user followers and following, Set Limit of data in feeds
#### Repository
https://github.com/python

#### What Will I Learn?
- List user followers and following
- Set Limit of data in feeds

#### Requirements
- Basic Python
- Install Python 3
- Install Flask


#### Resources
- Python - https://www.python.org/
- Flask - http://flask.pocoo.org/
- Peewee http://docs.peewee-orm.com/en/latest/
- Sqlitebrowser https://sqlitebrowser.org/

#### Difficulty
Basic

### Tutorial Content

I will continue my tutorial series on social media applications using the flask, so far we have made several features including database structure, authentication systems, feeds, notifications, following systems and user profiles. this tutorial I will complete the application that we have made by making a list of followers and following. for those of you who are just following this tutorial, you can see the development of this tutorial in the curriculum section. okay, I just started this tutorial.


### List followers and following

- **List following**

I will add information that is important and often we encounter on social media based applications. In this section, I will create a list of lists of users that we have followed or who follow us. I will start by creating a new routing that is ```@app.route('/user/<username>/following')```. For more details, we can see the following example

**app.py**

```
@app.route('/user/<username>/following')
def showFollowing(username):
	try:
		user = User.get(User.username == username)
	except User.DoesNotExist:
		abort(404)
	return render_template('userList.html', users = user.following())
```

- In this routing, I will pass the username parameters of the user who is logged in ```@app.route('/user/<username>/following')```.

- And then I will add a new template **userList.html**. In the previous [tutorial](https://steemit.com/utopian-io/@duski.harahap/make-social-media-applications-with-flask-8-handle-error-and-make-the-system-follow-a-user-1549792437933), I made a *relation* for the user who followed us. The following is a function that we have made in the previous tutorial.

**User model**

```
	def following(self):
		return (User.select()
					.join(Relationship, on=Relationship.to_user)
					.where(Relationship.from_user == self)
					.order_by(User.username))
```

- System following that I join between table relationship and user table ```.join(Relationship, on=Relationship.to_user)```. So now we can know who are the users we have *followed*. In this function, I join the user table with the ```Relationship.to_user``` field.

- After we get the results we can return it in the template **userList.html**. We can return it as follows ```return render_template('userList.html', users = user.following())```. I passed the value ```user.following ()``` to key **users**.
<br>

- **List followers**

Not much different from following me I will also make new followers, different functions are those that we use to get user followers. to see the difference we can see the code below:

**app.py**

```
@app.route('/user/<username>/followers')
def showFollowers(username):
	try:
		user = User.get(User.username == username)
	except User.DoesNotExist:
		abort(404)
	return render_template('userList.html', users = user.followers())
```

I will use the same template, userList.html, but I will use a different function that we made in the previous [tutorial](https://steemit.com/utopian-io/@duski.harahap/make-social-media-applications-with-flask-8-handle-error-and-make-the-system-follow-a-user-1549792437933). I will use the ```followers ()``` function in the following user models:

**User model**

```
	def followers(self):
		return (User.select()
					.join(Relationship, on=Relationship.from_user)
					.where(Relationship.to_user == self)
					.order_by(User.username))
```

 In this function I join the **user table** with the ```Relationship.from_user``` field and then the results will be returned on the **userList.html** page, ```return render_template('userList.html', users = user.followers())```.
 <br>

- **Show list in frontend**

Then I will add ```url_for()``` on the button that we made earlier in the frontend section so that it can be clicked on and linked to the user list.

**profile.html**

```
{%extends "layout.html" %}
{% block body %}
<div class="jumbotron">
	{% if user.username != session.username %}
		{% if active_user.is_following(user)%}
			<form method="post" action="{{url_for('userUnfollow', username = user.username)}}">
				<p class="bold">{{user.username}} <button class="btn btn-danger">-Unfollow</button></p>
			</form>
		{% else %}
			<form method="post" action="{{url_for('userFollow', username = user.username)}}">
				<p class="bold">{{user.username}} <button class="btn btn-primary">+Follow</button></p>
			</form>
		{% endif %}
	{% endif %}
  <hr>
    <a href="{{url_for('showFollowers', username = user.username)}}" class="btn btn-primary">
  		Follower <span class="badge badge-light">{{user.followers() | length}} </span>
  	</a>
  	<a href="{{url_for('showFollowing', username = user.username)}}" class="btn btn-success">
  		Following <span class="badge badge-light">{{user.following() | length}} </span>
  	</a>
  <h1 class="display-4">Welcome to homepage {{user.username}}, I'm using base layout</h1>
  <p class="lead">Welcome to the social media application that uses flasks</p>
  <hr class="my-4">
  <h2 style="text-align: center;">Your feed</h2>
  {% for message in messages%}
		<h4>{{message.content}}</h4>
		<span style="font-size: 10px; font-style: italic;">{{message.published_at}}</span>
  {% endfor %}
</div>
{% endblock %}
```

- I will tag ```<a>``` button and link with ```url_for ()``` we can adjust to the functions that we have made in each of the routings. 
For list **followers** we can link to routing:

```url_for('showFollowers', username = user.username)```

For list **following** :

```url_for('showFollowing', username = user.username)```
<br>
- **Display User following and followers**

Then we just have to show the data that we have shifted to the frontend, which is **userList.html**.

**userList.html**


```
{%extends "layout.html" %}
{% block body %}
<div class="jumbotron">
  <h2 style="text-align: center;">User list</h2>
  {% for user in users%}
		<a href="{{url_for('userProfile', username=user.username)}}">{{user.username}}</a>
  {% endfor %}
</div>
{% endblock %}
```

Because the user follows and user followed can be more than one, then I will loop the users object that we have shifted to the backend.

```
{% for user in users%}
		<a href="{{url_for('userProfile', username=user.username)}}">{{user.username}}</a>
  {% endfor %}
```

- When displaying I will also link the user with **userProfile** so that we can go directly to the user profile page that we are headed. we can do this by using the userProfile function and passing the username to the routing like this ```url_for('userProfile', username=user.username)```

- If everything is finished and there is no error then we can see the results as shown below:
I will log in as a user of ***milleaduski1994***.

![ezgif.com-video-to-gif.gif](https://cdn.steemitimages.com/DQmTAnsGq5ciu3YZVJ4yqsygTWn6ueH2yVjsPzM7fRAr8Xd/ezgif.com-video-to-gif.gif)

As we can see in the picture above we have successfully displayed users who follow us and we have followed and also we have linked the profiles of each user list.

![ezgif.com-video-to-gif (1).gif](https://cdn.steemitimages.com/DQmUJqbWLAHZsrC7BnD2ZNfrJ2rpFtK6Mt3x7n9ULRb2wh9/ezgif.com-video-to-gif%20(1).gif)
<br>
- **Limit feeds**

There is one feature that I will make on our application, try to imagine when we have followed many users and their posts appear on our homepage, of course, there will be very many posts on the homepage. for that, I will limit the status that can appear on our homepage. We can create a limit when retrieving data that is in our database, for more details we can see in the code below:

**app.py**

```
def showHomePage():
	user = get_current_user()
	messages = (Message.select()
				.where((Message.user << user.following()) |
					(Message.user == user.id)
				)
				.order_by(Message.published_at.desc()).limit(3)
		)
```

We can use the ```limit ()``` function in the **pewee**, We can pass for numbers as the number we want to display ```.limit(3)```.


![ezgif.com-video-to-gif (2).gif](https://cdn.steemitimages.com/DQmYwpFrusDzWuaYcdiyH3ZhgxVcvcvriXvL2oJXcu9v8XL/ezgif.com-video-to-gif%20(2).gif)

![Screenshot_1.png](https://ipfs.busy.org/ipfs/QmR7oChWx1yAMnVq4eGeUUwk7indaupVx37xAQsoKfaFZh)

We can see in the picture above we have limited the data that will be displayed and we have also created a user list of followers and following, then I end my tutorial this time, in the next tutorial I will use ajax jquery to make the limits more dynamic. I hope this tutorial can be useful for you, thank you.


### Curriculum

[Make social media applications with Flask #1: Design database and initial structure, Following and follower functions](
https://steemit.com/utopian-io/@duski.harahap/make-social-media-applications-with-flask-1-desaign-database-and-initial-structure-following-and-follower-functions-1547568096688)

[Make social media applications with Flask #2: System routing and Templating, Make user register](https://steemit.com/utopian-io/@duski.harahap/make-social-media-applications-with-flask-2-system-routing-and-templating-make-user-register-1547816234338)

[Make social media applications with Flask #3: Register user and Store data in SQLite, Base Layout](https://steemit.com/utopian-io/@duski.harahap/make-social-media-applications-with-flask-3-register-user-and-store-data-in-sqlite-base-layout-1548251533384)

[Make social media applications with Flask #4: Login system and Use session to manage user data](https://steemit.com/utopian-io/@duski.harahap/make-social-media-applications-with-flask-4-login-system-and-use-session-to-manage-user-data-1548429289119)

[Make social media applications with Flask #5:  Authentication during registration and User notification](
https://steemit.com/utopian-io/@duski.harahap/make-social-media-applications-with-flask-5-authentication-during-registration-and-user-notification-1548686390863)

[Make social media applications with Flask #6:  View decorator and Post the first status](https://steemit.com/utopian-io/@duski.harahap/make-social-media-applications-with-flask-6-view-decorator-and-post-the-first-status-1549029740369)

[Make social media applications with Flask #7:  The use of backref and Create profile features](
https://steemit.com/utopian-io/@duski.harahap/make-social-media-applications-with-flask-7-the-use-of-backref-and-create-profile-features-1549339256879)

[Make social media applications with Flask #8: Handle error and Make the system follow a user](
https://steemit.com/utopian-io/@duski.harahap/make-social-media-applications-with-flask-8-handle-error-and-make-the-system-follow-a-user-1549792437933)

#### Proof of work done

https://github.com/milleaduski/python-web-app
๐Ÿ‘  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 78 others
properties (23)
authorduski.harahap
permlinkmake-social-media-applications-with-flask-12-list-user-followers-and-following-set-limit-of-data-in-feeds-1551105364701
categoryutopian-io
json_metadata{"app":"steeditor/0.1.2","format":"markdown","image":["https://ipfs.busy.org/ipfs/QmR7oChWx1yAMnVq4eGeUUwk7indaupVx37xAQsoKfaFZh","https://cdn.steemitimages.com/DQmTAnsGq5ciu3YZVJ4yqsygTWn6ueH2yVjsPzM7fRAr8Xd/ezgif.com-video-to-gif.gif","https://cdn.steemitimages.com/DQmUJqbWLAHZsrC7BnD2ZNfrJ2rpFtK6Mt3x7n9ULRb2wh9/ezgif.com-video-to-gif%20(1","https://cdn.steemitimages.com/DQmYwpFrusDzWuaYcdiyH3ZhgxVcvcvriXvL2oJXcu9v8XL/ezgif.com-video-to-gif%20(2","https://ipfs.busy.org/ipfs/QmR7oChWx1yAMnVq4eGeUUwk7indaupVx37xAQsoKfaFZh"],"tags":["utopian-io","tutorials","python","web","flask"],"users":["app","duski"],"links":["https://github.com/python","https://www.python.org/","http://flask.pocoo.org/","http://docs.peewee-orm.com/en/latest/","https://sqlitebrowser.org/","https://steemit.com/utopian-io/@duski.harahap/make-social-media-applications-with-flask-8-handle-error-and-make-the-system-follow-a-user-1549792437933","https://cdn.steemitimages.com/DQmUJqbWLAHZsrC7BnD2ZNfrJ2rpFtK6Mt3x7n9ULRb2wh9/ezgif.com-video-to-gif%20","https://cdn.steemitimages.com/DQmYwpFrusDzWuaYcdiyH3ZhgxVcvcvriXvL2oJXcu9v8XL/ezgif.com-video-to-gif%20","https://steemit.com/utopian-io/@duski.harahap/make-social-media-applications-with-flask-1-desaign-database-and-initial-structure-following-and-follower-functions-1547568096688","https://steemit.com/utopian-io/@duski.harahap/make-social-media-applications-with-flask-2-system-routing-and-templating-make-user-register-1547816234338","https://steemit.com/utopian-io/@duski.harahap/make-social-media-applications-with-flask-3-register-user-and-store-data-in-sqlite-base-layout-1548251533384","https://steemit.com/utopian-io/@duski.harahap/make-social-media-applications-with-flask-4-login-system-and-use-session-to-manage-user-data-1548429289119","https://steemit.com/utopian-io/@duski.harahap/make-social-media-applications-with-flask-5-authentication-during-registration-and-user-notification-1548686390863","https://steemit.com/utopian-io/@duski.harahap/make-social-media-applications-with-flask-6-view-decorator-and-post-the-first-status-1549029740369","https://steemit.com/utopian-io/@duski.harahap/make-social-media-applications-with-flask-7-the-use-of-backref-and-create-profile-features-1549339256879","https://github.com/milleaduski/python-web-app"]}
created2019-02-25 14:36:15
last_update2019-02-25 14:36:15
depth0
children5
last_payout2019-03-04 14:36:15
cashout_time1969-12-31 23:59:59
total_payout_value17.886 HBD
curator_payout_value5.935 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length11,000
author_reputation60,094,717,098,672
root_title"Make social media applications with Flask #12: List user followers and following, Set Limit of data in feeds"
beneficiaries
0.
accountutopian.pay
weight500
max_accepted_payout100,000.000 HBD
percent_hbd10,000
post_id80,374,737
net_rshares41,220,521,935,943
author_curate_reward""
vote details (142)
@partiko ·
Hello @duski.harahap! This is a friendly reminder that you have 3000 Partiko Points unclaimed in your Partiko account!

Partiko is a fast and beautiful mobile app for Steem, and itโ€™s the most popular Steem mobile app out there! Download Partiko using the link below and login using SteemConnect to claim your 3000 Partiko points! You can easily convert them into Steem token!

https://partiko.app/referral/partiko
properties (22)
authorpartiko
permlinkpartiko-re-duski-harahap-make-social-media-applications-with-flask-12-list-user-followers-and-following-set-limit-of-data-in-feeds-1551105364701-20190226t115430253z
categoryutopian-io
json_metadata{"app":"partiko"}
created2019-02-26 11:54:30
last_update2019-02-26 11:54:30
depth1
children0
last_payout2019-03-05 11:54:30
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length413
author_reputation39,207,160,334,751
root_title"Make social media applications with Flask #12: List user followers and following, Set Limit of data in feeds"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id80,432,973
net_rshares0
@portugalcoin ·
$10.96
Thank you for your contribution @duski.harahap.
After analyzing your tutorial we suggest the following points below:

- Using the first person in the tutorials makes it difficult to understand the tutorials. We suggest using the third person in your text.

- Put comments in your code sections. The comments are very important and help a lot less experienced users.

- Try to improve your writing in the tutorial. Tutorials need to be well written.

Your contribution has been evaluated according to [Utopian policies and guidelines](https://join.utopian.io/guidelines), as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, [click here](https://review.utopian.io/result/8/3-1-2-1-3-3-2-3-).

---- 
Need help? Chat with us on [Discord](https://discord.gg/uTyJkNm).

[[utopian-moderator]](https://join.utopian.io/)
๐Ÿ‘  , , , , , , , , , , , , , , , , , , ,
properties (23)
authorportugalcoin
permlinkre-duskiharahap-make-social-media-applications-with-flask-12-list-user-followers-and-following-set-limit-of-data-in-feeds-1551105364701-20190225t215212067z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"users":["duski.harahap"],"links":["https://join.utopian.io/guidelines","https://review.utopian.io/result/8/3-1-2-1-3-3-2-3-","https://discord.gg/uTyJkNm","https://join.utopian.io/"],"app":"steemit/0.1"}
created2019-02-25 21:52:18
last_update2019-02-25 21:52:18
depth1
children1
last_payout2019-03-04 21:52:18
cashout_time1969-12-31 23:59:59
total_payout_value8.331 HBD
curator_payout_value2.631 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length900
author_reputation599,460,589,822,571
root_title"Make social media applications with Flask #12: List user followers and following, Set Limit of data in feeds"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id80,391,234
net_rshares18,474,356,465,663
author_curate_reward""
vote details (20)
@utopian-io ·
Thank you for your review, @portugalcoin! Keep up the good work!
properties (22)
authorutopian-io
permlinkre-re-duskiharahap-make-social-media-applications-with-flask-12-list-user-followers-and-following-set-limit-of-data-in-feeds-1551105364701-20190225t215212067z-20190228t115706z
categoryutopian-io
json_metadata"{"app": "beem/0.20.17"}"
created2019-02-28 11:57:09
last_update2019-02-28 11:57:09
depth2
children0
last_payout2019-03-07 11:57:09
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length64
author_reputation152,955,367,999,756
root_title"Make social media applications with Flask #12: List user followers and following, Set Limit of data in feeds"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id80,532,226
net_rshares0
@steemitboard ·
Congratulations @duski.harahap! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

<table><tr><td>https://steemitimages.com/60x70/http://steemitboard.com/@duski.harahap/voted.png?201902260653</td><td>You received more than 5000 upvotes. Your next target is to reach 6000 upvotes.</td></tr>
</table>

<sub>_[Click here to view your Board](https://steemitboard.com/@duski.harahap)_</sub>
<sub>_If you no longer want to receive notifications, reply to this comment with the word_ `STOP`</sub>



> Support [SteemitBoard's project](https://steemit.com/@steemitboard)! **[Vote for its witness](https://v2.steemconnect.com/sign/account-witness-vote?witness=steemitboard&approve=1)** and **get one more award**!
properties (22)
authorsteemitboard
permlinksteemitboard-notify-duskiharahap-20190226t122802000z
categoryutopian-io
json_metadata{"image":["https://steemitboard.com/img/notify.png"]}
created2019-02-26 12:28:00
last_update2019-02-26 12:28:00
depth1
children0
last_payout2019-03-05 12:28:00
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length766
author_reputation38,975,615,169,260
root_title"Make social media applications with Flask #12: List user followers and following, Set Limit of data in feeds"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id80,434,841
net_rshares0
@utopian-io ·
Hey, @duski.harahap!

**Thanks for contributing on Utopian**.
Weโ€™re already looking forward to your next contribution!

**Get higher incentives and support Utopian.io!**
 Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via [SteemPlus](https://chrome.google.com/webstore/detail/steemplus/mjbkjgcplmaneajhcbegoffkedeankaj?hl=en) or [Steeditor](https://steeditor.app)).

**Want to chat? Join us on Discord https://discord.gg/h52nFrV.**

<a href='https://steemconnect.com/sign/account-witness-vote?witness=utopian-io&approve=1'>Vote for Utopian Witness!</a>
properties (22)
authorutopian-io
permlinkre-make-social-media-applications-with-flask-12-list-user-followers-and-following-set-limit-of-data-in-feeds-1551105364701-20190226t152028z
categoryutopian-io
json_metadata"{"app": "beem/0.20.17"}"
created2019-02-26 15:20:30
last_update2019-02-26 15:20:30
depth1
children0
last_payout2019-03-05 15:20:30
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length595
author_reputation152,955,367,999,756
root_title"Make social media applications with Flask #12: List user followers and following, Set Limit of data in feeds"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id80,445,573
net_rshares0