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 trialpeterbristow
10,403 PointsNot displaying data from db correctly in index.html page
So I created an "Add a Taco form" then I added a Taco. Then when I try to display the Taco in the index page I get the following "(<peewee.CharField object at 0x7fb77a6bb128>,)" instead of the data. We the fraggle is going on?
Please Help me. Here is my code:
import datetime
from flask.ext.bcrypt import generate_password_hash
from flask.ext.login import UserMixin
from peewee import *
DATABASE = SqliteDatabase('taco.db')
class User(UserMixin, Model):
email = CharField(unique=True)
password = CharField(max_length=100)
joined_at = DateTimeField(default=datetime.datetime.now)
class Meta:
database = DATABASE
order_by = ('-joined_at', )
@classmethod
def create_user(cls, email, password):
try:
with DATABASE.transaction():
cls.create(
email=email,
password=generate_password_hash(password)
)
except IntegrityError:
raise ValueError("User already exists.")
class Taco(Model):
timestamp = DateTimeField(default=datetime.datetime.now)
user = ForeignKeyField(
rel_model=User,
related_name='tacos'
)
protein = CharField(max_length=100),
shell = CharField(max_length=100),
cheese = BooleanField(default=False),
extras = CharField(max_length=255)
class Meta:
database = DATABASE
order_by = ('-timestamp',)
def initialize():
DATABASE.connect()
DATABASE.create_tables([User], safe=True)
DATABASE.close()
from flask_wtf import Form
from wtforms import StringField, PasswordField, BooleanField
from wtforms.validators import (DataRequired, Regexp, ValidationError, Email, Length, EqualTo)
from models import User
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):
email = StringField(
'Email',
validators=[
DataRequired(),
Email(),
email_exists
]
)
password = PasswordField(
'Password',
validators=[
DataRequired(),
Length(min=8),
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 TacoForm(Form):
protein = StringField(
'Protein',
validators=[
DataRequired(),
Regexp(
r'^[a-zA-Z]+$',
message=("That is not a protein, use letters only")
)
]
)
shell = StringField(
'Shell',
validators=[
DataRequired(),
Regexp(
r'^[a-zA-Z]+$',
message=("That is not a shell, use letters only")
)
]
)
cheese = BooleanField('Cheese')
extras = StringField('Extras')
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 = 'asdfasdfasf'
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():
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.RegisterForm()
if form.validate_on_submit():
flash('You are now registered!', "success")
models.User.create_user(
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("Email or password don't match", "error")
else:
if check_password_hash(user.password, form.password.data):
login_user(user)
return redirect(url_for('index'))
else:
flash("Email or password don't match", "error")
return render_template('login.html', form=form)
@app.route('/logout')
@login_required
def logout():
logout_user()
flash("You are now Logged out!", "success")
return redirect(url_for('index'))
@app.route('/taco', methods=('GET', 'POST'))
@login_required
def taco():
form = forms.TacoForm()
if form.validate_on_submit():
models.Taco.create(
user=g.user._get_current_object(),
protein=form.protein.data,
shell=form.shell.data,
cheese=form.cheese.data,
extras=form.extras.data
)
flash("Taco created!", "success")
return redirect(url_for('index'))
return render_template("taco.html", form=form)
@app.route('/')
def index():
tacos = models.Taco.select().limit(30)
return render_template('index.html', tacos=tacos)
if __name__ == '__main__':
models.initialize()
app.run(debug=DEBUG, host=HOST, port=PORT)
{% extends 'layout.html' %}
{% block content %}
<h2>Tacos</h2>
{% if tacos.count() %}
<table class="u-full-width">
<thead>
<tr>
<th>Protein</th>
<th>Cheese?</th>
<th>Shell</th>
<th>Extras</th>
</tr>
</thead>
<tbody>
{% for taco in tacos %}
<tr>
<!-- taco attributes here -->
<td>{{ taco.protein }}</td>
<td>{{ taco.cheese }}</td>
<td>{{ taco.shell }}</td>
<td>{{ taco.extras }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<!-- message for missing tacos -->
<p>No tacos yet</p>
{% endif %}
{% endblock %}
2 Answers
Chris Freeman
Treehouse Moderator 68,457 PointsThe debug was tricky with this one.
- No
Taco
instances were being created intaco.db
since theTaco
model was not listed in theDATABASE.create_tables
line.
Changed to: DATABASE.create_tables([User, Taco], safe=True)
- Once added to the database not all fields were seen. only: "id", "timestamp", "user_id", "extras", "user_id"
$ sqlite3 taco.db
SQLite version 3.8.2 2013-12-06 14:53:30
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .dump taco
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE "taco" ("id" INTEGER NOT NULL PRIMARY KEY, "timestamp" DATETIME NOT NULL, "user_id" INTEGER NOT NULL, "extras" VARCHAR(255) NOT NULL, FOREIGN KEY ("user_id") REFERENCES "user" ("id"));
CREATE INDEX "taco_user_id" ON "taco" ("user_id");
COMMIT;
- The missing fields were the clue. Looking at the model definition:
class Taco(Model):
timestamp = DateTimeField(default=datetime.datetime.now)
user = ForeignKeyField(
rel_model=User,
related_name='tacos'
)
protein = CharField(max_length=100), # <-- comma should not be here
shell = CharField(max_length=100), # <-- comma should not be here
cheese = BooleanField(default=False), # <-- comma should not be here
extras = CharField(max_length=255)
Removing the commas fixed the issue.
Ken Alger
Treehouse TeacherPeter;
Can you post the code you are using please? It will greatly assist in troubleshooting your problem.
Thanks,
Ken
peterbristow
10,403 PointsHi Ken
I just added my code for all to see.
Thanks, Peter.
Chris Freeman
Treehouse Moderator 68,457 PointsThis would be better as a comment than an answer so from the community page it looks like the question still needs answering.