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 Broadcasting Lunch Template

What did I not understand?

I am so lost with this that I feel silly. Just throw me a bone, and give me a hint what segments I need to re-watch to remember and understand how it goes together. Yesterday, I got it to tell me that I had the date part right, but not the lunch. But today, I don't get that. Thanks.

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'))
templates/today.html
{% extends "layout.html" %}

{% block content %}
<h1>Your lunch for today</h1>

<h2><!-- today's date -->{{ date.data.strftime('%Y-%m-%d') }}</h2>
<p><!-- print today's lunch order --></p>
<!-- button to the route for cancel_order with order_id=order.id -->
{% endblock %}

Thanks so much.

I got the , but I am not quite sure if I quite understand the logic behind it. In other words, what or where does the 'first'dot'second' as in "order" and "date" relate back to?

3 Answers

You don't need to do any modifications to the views. You do need to work with the "order" variable past through the '/today' view. The 'order' variable contains the 'order' and 'date' attributes of the object. So, without telling you the whole answer it would be something like 'order.date' and 'order.order'.

Hi Rune,

Hopefully you weren't as confused by those trying to help you in this forum thread as I was.

The videos and the zip download for this course have been ABSOLUTELY no help either,

so I just ended up "guessing" my way through the Lunch Template challenge:

http://teamtreehouse.com/library/build-a-social-network-with-flask/broadcasting/lunch-template

..using code sorta like this:

{% extends "layout.html" %}

{% block content %}
<h1>Your lunch for today</h1>

<h2><!-- today's date -->{{ order.date.strftime('%Y-%m-%d') }}</h2>
<p><!-- print today's lunch order -->{{ order.order }}</p>
<!-- button to the route for cancel_order with order_id=order.id -->
<a href="{{url_for('cancel_order', order_id= order.id) }}>Cancel Order</a>
{% endblock %}

Just wait to you get to the Tacocat challenge at the end..that's the real doozy!

**Wow, the code blocks did not get formatted properly. What am I doing wrong?

Anyways...

I wish the challenge would have included a tab to view the 'models.py' file, but you can take a look at the '/orders' view to understand the construction of the 'LunchOrder' object.

@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)

A LunchOrder has a user, date and order attribute. So when you retrieve a LunchOrder like we did in the '/today' view:

@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)

It is retrieving a single LunchOrder object with the date and order attributes attached. Then in 'render_template', not only do you choose which template you want to use, but you pass in any variables you want to display in the template. In our case, the LunchOrder object is stored in the variable 'order' and passed to 'today.html' as the name 'order'.

Then in the 'today.html' template you can access the attributes of the LunchOrder object (stored as 'order') by using {{ order.date }} and {{ order.order }}.

Hi @cassac, to format the code blocks you need to use three backtick characters (usually to the left of the 1 key), not a single quote:

backtick: `
single quote: '

There also needs to be a blank line before and after the backticks.

You can also use a single backtick on either side of text in a paragraph to use the inline code formatting (good for variable or file names, etc).

e.g. This:

Then in the `today.html` template you can access the attributes of the `LunchOrder` object (stored as `order`) by using `{{ order.date }}` and `{{ order.order }}`.

Will display like this:

Then in the today.html template you can access the attributes of the LunchOrder object (stored as order) by using {{ order.date }} and {{ order.order }}.