Make social media applications with Flask #7: The use of backref and Create profile features

in #utopian-io5 years ago

Repository

https://github.com/python

What Will I Learn?

  • The use of backref
  • Create profile features

Requirements

  • Basic Python
  • Install Python 3
  • Install Flask

Resources

Difficulty

Basic

Tutorial Content

We continue my next tutorial series about social media applications using Flask. In my previous tutorial, we learned how to make a new post. In this tutorial, I will make an important part of the social media application, the profile page. as the name implies this page will handle all information related to the user. therefore we need to pay attention to the user model that we have made in the previous tutorials. for those of you who haven't followed my tutorial before, you can see other tutorials in the curriculum section. Okay we just start the tutorial this time.

User model relations

We will learn the relation to the model if you follow the first tutorial series. I have created a User model to create abstractions from our database table. The user table has several columns as we see in the following user model.

app.py

class User(BaseModel):
    username = CharField(unique=True)
    password = CharField()
    email = CharField(unique=True)
    join_at = DateTimeField(default=datetime.datetime.now())

As we saw above we have columns for username, password, email, and join_at. and has a unique value in the user name and email column.

  • Add new route

To create a profile page, of course, I will create a new route, because the profile page is dynamic and depending on the user who is logged in, we can use parameters on the routing, here is how:

app.py

@app.route('/user/<username>') // The parameter is the username
def userProfile(username): // define function and pass the parameter
  • to pass dynamic parameters to the route we can use < >. The name will be the parameter that we shift the functions we define like this def userProfile(username):.

  • The use of backref

when I make my model give a backref to the column as a reference to the name of the column, we can now see its use to be a data abstraction from the column that we can use to manipulate that data. We will see an example of its use as below:

app.py

@app.route('/user/<username>')
def userProfile(username):
    user = User.get(User.username == username) // get user data from the username
    messages = user.Messages.order_by(Messages.published_at.desc()) // get the all messages from the user 
    return render_template('profile.html', messages = messages, user=user) // pass the paramter to the profile page
  • User.get(): to get user data we can use the get() function in the model name we use, this example I use the User model. So I can retrieve user data based on the username that has been passed in the parameter User.get(User.username = username).

  • backref Messages: When creating a user model we define backref = Messages in the user column. So we can use it as an alias from our data.

Screenshot_1.png

  • Get User Messages: to get a user message we can use Backref Message, I will use the order_by() function to sort the latest messages or posts from the user based on the dates we get from published_at user.Messages.order_by(Messages.published_at.desc()).

  • And after all the data we have got, we can restore it to the profile page like the following return render_template('profile.html', messages = messages, user=user). I will pass the first two parameters to the message and the second is the user data who is logged in.

  • Show data on profile page

We have finished the backend now I will forward the data to the frontend. on the front end, I will print out the username and messages from the user. The following is the appearance of the frontend:

profile.html

{%extends "layout.html" %}
{% block body %}
<div class="jumbotron">
  <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 %}
  • On the profile page, I will still use the base layout that we have, there are two data that we passed in the backend, the first is the user data and the second is the message or post of the user.

  • I will print out the user name in the data object, so we can print out the username by {{user.username}}.

  • And for data from messages, we can print out {% for message in messages%} because there are more than one message or post from the user. on message objects we have 3 data keys that we can use. The message on the key content and the post date is on published_at. The following is the Message Model.

Screenshot_2.png

After it's finished we can run our application with flask run, If there is no error then we can see the results as follows.

ezgif.com-video-to-gif.gif

We can see in the picture above that our status has appeared if we look at the database so we can see the data we see like this:

Table Message

ezgif.com-video-to-gif (1).gif

  • Add a new post in the profile

After that, I will test whether the latest post I made will enter my profile page. we can see the results of the demonstration in the picture below:

ezgif.com-video-to-gif (2).gif

Table Message

ezgif.com-video-to-gif (3).gif

We can see that there is a new record in the message table, this means that we have linked the user message table and table through the backref

  • User page redirect

If we look at the examples above, after we create a new status, we are directed directly to the home page. now I will navigate to the profile page. for that we can make some changes in the code:

app.py

@app.route('/add-post', methods =['GET', 'POST'])
@login_required
def createPost():
    user = get_current_user()
    if request.method == 'POST' and request.form['content']:
        message = Message.create(
            user         = user,
            content      = request.form['content']
        )
        flash('Your status has been updated successfully')
        # Before
        # return redirect(url_for('showHomePage'))
        # After
        return redirect(url_for('userProfile', username = user.username)) // we must to pass the paramter username
    return render_template('newPost.html')

As we see we have to pass our mandatory parameters on route '/user/<username>'. We can get our username through the function we have used above, that is user = get_current_user().

And now we will demonstrate again the results of the code changes that we did as shown below:

ezgif.com-video-to-gif (4).gif

We can see in the picture above, we redirect to the profile page of the user who is logged in, this means that we have successfully created the profile feature in the application, thank you for following my tutorial. hopefully useful

  • Web development with flask

Web developement with python #1 : Flask initialization and Routing system

Web development with python #6 : Use flash message and combine it with framework boostrap

  • File in python

File in python #1 : Read file and Write file and Modes file

  • Class-based views

Tutorial Django - Class based views #1 : Installation and configuration Django, Using a template system



Create Aplication social media with flask

Make social media applications with Flask #1: Design database and initial structure, Following and follower functions

Make social media applications with Flask #2: System routing and Templating, Make user register

Make social media applications with Flask #3: Register user and Store data in SQLite, Base Layout

Make social media applications with Flask #4: Login system and Use session to manage user data

Make social media applications with Flask #5: Authentication during registration and User notification

Make social media applications with Flask #6: View decorator and Post the first status

Proof of work done

https://github.com/milleaduski/python-web-app

Sort:  

I thank you for your contribution. Here are my thoughts. Note that, my thoughts are my personal ideas on your post and they are not directly related to the review and scoring unlike the answers I gave in the questionnaire;

  • Language

    • Lack of grammar and vocabulary makes your tutorial harder to understand. I advise you to proofread before posting and improvising yourself in general.

    • Usage of the first person makes tutorials harder to comprehend. If I were you, I would try my best to use the third person by changing the subjects of the sentences. I advise you to do that.

  • Content

    • As @portugalcoin stated, it's repetitive. If you showed how routes work with an example, in the next tutorial, show something else instead of just showing routes again with a different example. By doing that, you can reduce repetitiveness by a great amount.

Your contribution has been evaluated according to Utopian policies and 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.


Need help? Chat with us on Discord.

[utopian-moderator]

Thank you for your review, @yokunjon! Keep up the good work!

✅ Enjoy the vote! For more amazing content, please follow @themadcurator for a chance to receive more free votes!

Hi @duski.harahap!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
Feel free to join our @steem-ua Discord server

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 or Steeditor).

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

Vote for Utopian Witness!

Coin Marketplace

STEEM 0.35
TRX 0.12
JST 0.040
BTC 70557.88
ETH 3560.83
USDT 1.00
SBD 4.75