Google App Engine – How to build a user profile page with webapp2

The idea of building a unique page for each user is very similar to building a page for each post. You can simply use the ID of a user entity. Since I already have an entity for user, I do not need to create another one. Therefore, I only need to create a class.

Before we write our profile class, let’s start with our template first (I am using Jinja2 template).  In this example, I can login to the website and once I login, there is a “profile” text which is just a link to my profile page. The key is to add a unique id to the link.  Check out the below code:
<a href="/profile/{{user.key.id()}}">Profile</a>

“user” is a variable that I am passing from my controller. By using

{{user.key.id()}}
I am able to get the id of a user entity, and I can use this as a unique link to the profile page of the user.

Let’s now move on to our profile class in the main.py. Of course, I need to add this to my url handler to map the profile link to the profile class. Below is the code for url mapping:
app = webapp2.WSGIApplication([('/', MainPage),
                               ('/profile/([0-9]+)', Profile),
                              ],
                              debug=True)
Since the id of each user is composed of numbers, I am using regular expression
([0-9]+)

which matches any number of integers. As well, by putting the regex inside the parentheses,  I can pass the user id to my profile class as an argument.

If you look at my profile class below, you will notice that it is taking another parameter.
class Profile(Handler):
    def get(self, profile_id):
        key = ndb.Key('User', int(profile_id), parent=users_key())
        user = key.get()

        self.render("profile.html", profile_user=user.name)

I can use the profile_id to get the key of the post and use the key to get the user entity.

Since I want some information of a user on the user profile page, I am passing the name of the user to display it on the profile page.

My user entity has a  “name” property so I can simply pass the name of the user and render my profile template with the variable. My profile.html file includes

{{profile_user}}

Once you render the template, you will see the name being displayed on the profile page.

That’s it! Happy coding 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s