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 Stream Views

Josh Keenan
Josh Keenan
20,315 Points

No post table

I have deleted and recreated the workspace 3 times now and I give up, I have copied the code and adjusted for syntax changes but every time I try to run the code after this stage, it won't run. I have no clue why, here's the code:

app.py

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, logout_user,
                             login_required, current_user)

import forms
import models

DEBUG = True
PORT = 8000
HOST = '0.0.0.0'

app = Flask(__name__)
app.secret_key = 'auoesh.bouoastuh.43,uoausoehuosth3ououea.auoub!'

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.get(models.User.id == userid)
    except models.DoesNotExist:
        return None


@app.before_request
def before_request():
    """Connect to the database before each request."""
    g.db = models.DATABASE
    g.db.connect()
    g.user = current_user


@app.after_request
def after_request(response):
    """Close the database connection after each request."""
    g.db.close()
    return response


@app.route('/register', methods=('GET', 'POST'))
def register():
    form = forms.RegisterForm()
    if form.validate_on_submit():
        flash("Yay, you registered!", "success")
        models.User.create_user(
            username=form.username.data,
            email=form.email.data,
            password=form.password.data
        )
        return redirect(url_for('index'))
    return render_template('register.html', form=form)


@app.route('/login', methods=('GET', 'POST'))
def login():
    form = forms.LoginForm()
    if form.validate_on_submit():
        try:
            user = models.User.get(models.User.email == form.email.data)
        except models.DoesNotExist:
            flash("Your email or password doesn't match!", "error")
        else:
            if check_password_hash(user.password, form.password.data):
                login_user(user)
                flash("You've been logged in!", "success")
                return redirect(url_for('index'))
            else:
                flash("Your email or password doesn't match!", "error")
    return render_template('login.html', form=form)


@app.route('/logout')
@login_required
def logout():
    logout_user()
    flash("You've been logged out! Come back soon!", "success")
    return redirect(url_for('index'))


@app.route('/new_post', methods=('GET', 'POST'))
@login_required
def post():
    form = forms.PostForm()
    if form.validate_on_submit():
        models.Post.create(user=g.user._get_current_object(),
                           content=form.content.data.strip())
        flash("Message posted", 'success')
        return redirect(url_for('index'))
    return render_template('post.html', form=form)


@app.route('/')
def index():
      stream = models.Post.select().limit(100)
      return render_template('stream.html', stream=stream)


@app.route('/stream')
@app.route('/stream/<username>')
def stream(username=None):
    template='stream.html'
    if username and username != current_user.username:
        user = models.User.select().where(models.User.username**username).get()
        stream = user.posts.limit(100)
    else:
        stream = current_user.get_stream().limit(100)
        user = current_user
    if username:
        template = 'user_stream.html'
    return render_template(template, stream=stream, user=user)


if __name__ == '__main__':
    models.initialize()
    try:
        models.User.create_user(
            username='kennethlove',
            email='kenneth@teamtreehouse.com',
            password='password',
            admin=True
        )
    except ValueError:
        pass
    app.run(debug=DEBUG, host=HOST, port=PORT)

==============================

models.py

import datetime
from wtforms import DateTimeField
from flask.ext.bcrypt import generate_password_hash
from flask.ext.login import UserMixin
from peewee import *

DATABASE = SqliteDatabase('social.db')

class User(UserMixin, Model):
    username = CharField(unique=True)
    email = CharField(unique=True)
    password = CharField(max_length=100)
    joined_at = DateTimeField(default=datetime.datetime.now)
    is_admin = BooleanField(default=False)

    class Meta:
        database = DATABASE
        order_by = ('-joined_at',)

    @classmethod
    def create_user(cls, username, email, password, admin=False):
        with DATABASE.transaction():
            try:
                cls.create(
                    username=username,
                    email=email,
                    password=generate_password_hash(password),
                    is_admin=admin)
            except IntegrityError:
                raise ValueError("User already exists")


class Post(Model):
    timestamp = DateTimeField(default=datetime.datetime.now)
    user = ForeignKeyField(
        rel_model=User,
        related_name='posts'
    )
    class Meta:
        database = DATABASE
        order_by = ('-timestamp',)


    def get_posts(self):
      return Post.select().where(
        (Post.user == self)
      )



def initialize():
    DATABASE.connect()
    DATABASE.create_tables([User], safe=True)
    DATABASE.close()

===========================

forms.py

from flask_wtf import Form
from wtforms import StringField, PasswordField, TextAreaField
from wtforms.validators import (DataRequired, Regexp, ValidationError, Email,
                               Length, EqualTo)

from models import User


def name_exists(form, field):
    if User.select().where(User.username == field.data).exists():
        raise ValidationError('User with that name already exists.')


def email_exists(form, field):
    if User.select().where(User.email == field.data).exists():
        raise ValidationError('User with that email already exists.')


class RegisterForm(Form):
    username = StringField(
        'Username',
        validators=[
            DataRequired(),
            Regexp(
                r'^[a-zA-Z0-9_]+$',
                message=("Username should be one word, letters, "
                         "numbers, and underscores only.")
            ),
            name_exists
        ])
    email = StringField(
        'Email',
        validators=[
            DataRequired(),
            Email(),
            email_exists
        ])
    password = PasswordField(
        'Password',
        validators=[
            DataRequired(),
            Length(min=2),
            EqualTo('password2', message='Passwords must match')
        ])
    password2 = PasswordField(
        'Confirm Password',
        validators=[DataRequired()]
    )


class LoginForm(Form):
    email = StringField('Email', validators=[DataRequired(), Email()])
    password = PasswordField('Password', validators=[DataRequired()])


class PostForm(Form):
    content = TextAreaField("What's up?", validators=[DataRequired()])

==========================

layout.html

<!DOCTYPE html>
<html class="no-js">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title>{% block title %}TwoCans{% endblock %}</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link href='http://fonts.googleapis.com/css?family=Varela+Round' rel='stylesheet' type='text/css'>
        <link rel="stylesheet" href="/static/css/normalize.min.css">
        <link rel="stylesheet" href="/static/css/main.css">

        <!--[if lt IE 9]>
            <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
            <script>window.html5 || document.write('<script src="/static/js/vendor/html5shiv.js"><\/script>')</script>
        <![endif]-->
    </head>
    <body>

        <header>

          <div class="row">

            <div class="grid-33">

              <a href="{{ url_for('index') }}" class="icon-logo"></a>

            </div>

            <div class="grid-33">

                <!-- Say Hi -->
                <h1>Hello{% if current_user.is_authenticated() %} {{ current_user.username }}{% endif %}!</h1>

            </div>

            <div class="grid-33">

                <!-- Log in/Log out -->
                {% if current_user.is_authenticated() %}
                <a href="{{ url_for('logout') }}" class="icon-power" title="Log out"></a>
                {% else %}
                <a href="{{ url_for('login') }}" class="icon-power" title="Log in"></a>
                <a href="{{ url_for('register') }}" class="icon-profile" title="Register"></a>
                {% endif %}

            </div>

          </div>

        </header>

        <!-- Flash messages -->
        {% with messages = get_flashed_messages(with_categories=True) %}
            {% if messages %}
                {% for category, message in messages %}
                    <div class="notification {{ category }}">{{ message }}</div>
                {% endfor %}
            {% endif %}
        {% endwith %}

        <div class="row">

          <div class="main">

            <nav>

              <a href="{{ url_for('index') }}">All</a>
                {% if current_user.is_authenticated %}
                <a href="{{ url_for('post') }}" class='new'>Create new post!</a>
                {% endif %}
            </nav>

            {% block content %}{% endblock %}

          </div>

        </div>

        <footer>

          <div class="row">

            <p>A Social App built with Flask<br>by <a href="http://teamtreehouse.com">Treehouse</a></p>

          </div>

        </footer>

        <script src="/static/js/vendor/disTime.min.js"></script>
        <script src="/static/js/main.js"></script>

    </body>
</html>

================

login.html

{% extends "layout.html" %}
{% from 'macros.html' import render_field %}

{% block content %}
<form method="POST" action="" class="form">
    {{ form.hidden_tag() }}
    {% for field in form %}
        {{ render_field(field) }}
    {% endfor %}
    <button type="submit" id="submit">Login!</button>
</form>
{% endblock %}

==================

macros.html

{% macro render_field(field) %}
    <div class="field">
        {% if field.errors %}
            {% for error in field.errors %}
                <div class="notification error">{{ error }}</div>
            {% endfor %}
        {% endif %}
        {{ field(placeholder=field.label.text) }}
    </div>
{% endmacro %}

===========

post.html

{% extends "layout.html" %}
{% from "macros.html" import render_field %}

{% block content %}
<form method='POST' action=''>
    {{ form.hidden_tag() }}
    {% for field in form %}
        {{ render_field(field) }}
    {% endfor %}
    <button type='submit' id='submit'>Post!</button>
</form>
{% endblock %}

=============

register.html

{% extends "layout.html" %}
{% from 'macros.html' import render_field %}

{% block content %}
<form method="POST" action="" class="form">
    {{ form.hidden_tag() }}
    {% for field in form %}
        {{ render_field(field) }}
    {% endfor %}
    <button type="submit" id="submit">Register!</button>
</form>
{% endblock %}

===============

stream.html

{% extends 'layout.html' %}

{% block content %}
{% for post in stream %}
    <article>
        <h2>
        <a href="{{ url_for('stream', username=post.user.username) }}">{{ post.user.username }}</a>
        </h2>
        <i class='clock'></i><time data-time="{{ post.timestamp }}" class='distime' datetime="{{ post.timestamp.strftime('%Y-%m-%d %H:%M:%S') }}">{{ post.timestamp.strftime('%Y-%m-%d %H:%M:%S') }}</time><a href='#' class='view'>View</a>
        <div class='post'>
            {{ post.content }}
        </div>
    </article>
{% endfor %}
{% endblock %}

======================

user_stream.html

{% extends 'stream.html' %}

{% block content %}
<div class='row'>
    <div class='grid-25'>
        <h1>{{ user.username }}</h1>
    </div>
    <div class='grid-50'>
        <div class='grid-33'>
            <h5>Posts</h5>
            <p>{{ user.posts.count() }}</p>
        </div>
        <div class='grid-33'>
            <h5>Followers</h5>
            <p>0</p>
        </div>
        <div class='grid-33'>
            <h5>Following</h5>
            <p>0</p>
        </div>
    </div>
    <div class='grid-25'>
        <!-- Follow/unfollow button -->
    </div>


</div>

{{ super() }}
{% endblock %}

=======================

[MOD: updated formatting using ```html+jinja -cf]

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,454 Points

Not sure if you're seeing the same error: AttributeError: 'bool' object has no attribute '__call__'

In layout.html, there seems to be an inconsistent use of is_authenticated with and without parens. Removing the parens seemed to clear up the error for me. You may need to add the missing parens, depending on if you system requires them. My setup does not like the trailing parens on is_authenticated

You also need to add Post to the models.initialize function:

 DATABASE.create_tables([User, Post], safe=True)
Josh Keenan
Josh Keenan
20,315 Points

No, thanks but that didn't work, I tried that before. The error is: peewee.OperationalError: no such table: post

Chris Freeman
Chris Freeman
Treehouse Moderator 68,454 Points

I forgot to include the update to models.initialize

Seth Reece
Seth Reece
32,867 Points

Hi Josh,

In your initialize method, you create a table for users, but not for posts. (In models.py) e.g.

def initialize():
    DATABASE.connect()
    DATABASE.create_tables([User, Post], safe=True)