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 trialJonathan Grenz
Python Development Techdegree Graduate 13,537 Pointspeewee.OperationalError: no such table: user
I had everything working beautifully until adding the 404 handling and then something broke. I've triple checked my code and rewatched the entire section and cannot see where the issue is. The problem lies when I attempt to view the stream of the current_user, that's when I get this error. I can view the stream of any other user, just not the current_user. This was not the case a few hours ago and unfortunately, I do not have a back up of my code from then. I would appreciate if I could get any thoughts on how to figure this out.
Here is my app.py:
from flask import (Flask, g, render_template, flash, redirect, url_for, abort)
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>')
@login_required
def stream(username=None):
template = 'stream.html'
if username and username != current_user.username:
try:
user = models.User.select().where(models.User.username**username).get()
except models.DoesNotExist:
abort(404)
else:
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)
@app.route('/post/<int:post_id>')
@login_required
def view_post(post_id):
posts = models.Post.select().where(models.Post.id == post_id)
if posts.count() == 0:
abort(404)
return render_template('stream.html', stream=posts)
@app.route('/follow/<username>')
@login_required
def follow(username):
try:
to_user = models.User.get(models.User.username**username)
except models.DoesNotExist:
abort(404)
else:
try:
models.Relationship.create(
from_user=g.user._get_current_object(),
to_user=to_user
)
except models.integrityError:
pass
else:
flash("You're now following {}.".format(to_user.username), "success")
return redirect(url_for('stream', username=to_user.username))
@app.route('/unfollow/<username>')
@login_required
def unfollow(username):
try:
to_user = models.User.get(models.User.username**username)
except models.DoesNotExist:
abort(404)
else:
try:
models.Relationship.get(
from_user=g.user._get_current_object(),
to_user=to_user
).delete_instance()
except models.integrityError:
pass
else:
flash("You unfollowed {}.".format(to_user.username), "success")
return redirect(url_for('stream', username=to_user.username))
@app.errorhandler(404)
def not_found(error):
return render_template('404.html'), 404
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)
And here is my models.py:
import datetime
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',)
def get_posts(self):
return Post.select().where(Post.user == self)
def get_stream(self):
return Post.select().where(
(Post.user << self.following()) |
(Post.user == self)
)
def following(self):
"""The users that we are following"""
return (
User.select().join(
Relationship, on=Relationship.to_user
).where(
Relationship.from_user == self
))
def followers(self):
"""Get users following the current user"""
return (
User.select().join(
Relationship, on=Relationship.from_user
).where(
Relationship.to_user == self
))
@classmethod
def create_user(cls, username, email, password, admin=False):
try:
with DATABASE.transaction():
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')
content = TextField()
class Mata:
database = DATABASE
order_by = {'-timestamp',}
def get_posts(self):
return Posts.select().where(Posts.user == self)
def get_stream(self):
return Posts.select().where(
(Posts.user == self)
)
class Relationship(Model):
from_user = ForeignKeyField(User, related_name='relationships')
to_user = ForeignKeyField(User, related_name='related_to')
class Meta:
database = DATABASE
indexes = (
(('from_user', 'to_user'), True)
)
def initialize():
DATABASE.connect()
DATABASE.create_tables([User, Post, Relationship], safe=True)
DATABASE.close()
1 Answer
KRIS NIKOLAISEN
54,971 PointsIn models.py class Post you have class Mata - it should be class Meta
class Post(Model):
timestamp = DateTimeField(default=datetime.datetime.now)
user = ForeignKeyField(rel_model=User, related_name='posts')
content = TextField()
class Mata:
database = DATABASE
order_by = {'-timestamp',}
Jonathan Grenz
Python Development Techdegree Graduate 13,537 PointsJonathan Grenz
Python Development Techdegree Graduate 13,537 PointsARRRGGG! I made the correction and sure enough, everything works. I knew it was going to be something like that. I can't think of how I did that considering it had worked already. Thanks for the second pair of eyes.