Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Build a Social Network with Flask How to Win Friends Follow/Unfollow views

rapharl hsu
rapharl hsu
3,476 Points

Code in the Challenge Task

I have a problem and I’m confused if I misunderstand the ‘where()’ in peewee or the codes in task “Follow/unfollow views” is wrong.

The following is the code in the task

    order = models.LunchOrder.select().where(
        id=order_id,
        user=g.user._get_current_object()
    ).get()

AND I write another one in the Flask Social app:

        relationship = models.Relationship.select().where(
            from_user=g.user._get_current_object(),
            to_user=to_user
            ).get()

The second one is wrong and even can’t run in python with syntax error:

File "app.py", line 171 from_user=g.user._get_current_object(), ^ SyntaxError: invalid character in identifier

The key point is I found the where() function in peewee API shows that

where(*expression)

and

       id=order_id,
        user=g.user._get_current_object()

these two parameters are not expressions I think.

I changed the code in the Flask Social app to:

 relationship = models.Relationship.select().where(
            (models.Relationship.from_user==g.user._get_current_object())&
            (models.Relationship.to_user==to_user)
            ).get()

then there is no problem.

So I highly doubt if the example code in the challenge task is wrong.

Can you answer that for me? Or you can just run the code in challenge task to make sure it is right and just let me know the result.

Then I can think about the problem in another way.

lunch.py
import datetime

from flask import Flask, g, render_template, flash, redirect, url_for
from flask.ext.bcrypt import check_password_hash
from flask.ext.login import LoginManager, login_user, current_user, login_required, logout_user

import forms
import models

app = Flask(__name__)
app.secret_key = 'this is our super secret key. do not share it with anyone!'
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'


@login_manager.user_loader
def load_user(userid):
    try:
        return models.User.select().where(
            models.User.id == int(userid)
        ).get()
    except models.DoesNotExist:
        return None


@app.before_request
def before_request():
    g.db = models.DATABASE
    g.db.connect()
    g.user = current_user


@app.after_request
def after_request(response):
    g.db.close()
    return response


@app.route('/register', methods=('GET', 'POST'))
def register():
    form = forms.SignUpInForm()
    if form.validate_on_submit():
        models.User.new(
            email=form.email.data,
            password=form.password.data
        )
        flash("Thanks for registering!") 
    return render_template('register.html', form=form)


@app.route('/login', methods=('GET', 'POST'))
def login():
    form = forms.SignUpInForm()
    if form.validate_on_submit():
        try:
            user = models.User.get(
                models.User.email == form.email.data
            )
            if check_password_hash(user.password, form.password.data):
                login_user(user)
                flash("You're now logged in!")
            else:
                flash("No user with that email/password combo")
        except models.DoesNotExist:
              flash("No user with that email/password combo")
    return render_template('register.html', form=form)

@app.route('/secret')
@login_required
def secret():
    return "I should only be visible to logged-in users"

@app.route('/logout')
def logout():
    logout_user()
    return redirect(url_for('login'))


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/order', methods=('GET', 'POST'))
def order_lunch():
    form = forms.LunchOrderForm()
    if form.validate_on_submit():
        models.LunchOrder.create(
            user=g.user._get_current_object(),
            date=form.date.data,
            order=form.order.data.strip()
        )
    return render_template('lunch.html', form=form)


@app.route('/today')
@login_required
def today():
    order = models.LunchOrder.select().where(
        models.LunchOrder.date == datetime.date.today() &
        models.LunchOrder.user == g.user._get_current_object()
    ).get()
    return render_template('today.html', order=order)


@app.route('/cancel_order/<int:order_id>')
@login_required
def cancel_order(order_id):
    try:
        order = models.LunchOrder.select().where(
            id=order_id,
            user=g.user._get_current_object()
        ).get()
    except models.DoesNotExist:
        pass
    else:
        order.delete_instance()
    return redirect(url_for('index'))

2 Answers

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

So I just tried this and I got it to pass. Two things that are a bit tricky.

  • @login_required has to come after the @app.route decorator.
  • Looking up the passed-in user requires you to use models.User.id in the lookup:
to_user = models.User.get(models.User.id==user_id)
rapharl hsu
rapharl hsu
3,476 Points

I got one TypeError: where() got an unexpected keyword argument 'from_user'

@app.route('/unfollow/<username>')
@login_required
def unfollow(username):
    try:
        to_user = models.User.get(models.User.username ** username)
        user_id = models.User.get(models.User.username ** username).id
    except models.DoesNotExist:
        abort(404)
    else:
        try:
            relationship = models.Relationship.select().where(
                from_user=g.user._get_current_object(),
                to_user=models.User.get(models.User.id == user_id)
            ).get()
        except models.IntegrityError:
            pass
        else:
            relationship.delete_instance()
            flash("You're now unfollowed {}!".format(
                to_user.username), "success")
    return redirect(url_for('stream', username=to_user.username))

what't the difference between my case with

order = models.LunchOrder.select().where(
            id=order_id,
            user=g.user._get_current_object()
        )

what't the correct usage of the function where()

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

Looking at the docs, it should be where(models.Relationship.from_user==g.user._get_current_object(),)

rapharl hsu
rapharl hsu
3,476 Points

Thanks for answering.

I do have read about the function where part of the docs of peewee. And I understand it just like the example you show in the comment.

What confused me is the following part

where(
            id=order_id,
            user=g.user._get_current_object()
        ).get()

I mean the following where function where(id=order_id,user=g.user._get_current_object())

I think it is conflict with the docs.