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 trialkacperwikiel
15,795 PointsRelationship between forms and views. How to provide both rendering template and receiving POST data in this case?
I am using return redirect in my code outside treehouse but i don't know how to solve this task without it.
from flask_wtf import Form
from wtforms import StringField, PasswordField, TextAreaField, DateField
from wtforms.validators import DataRequired, Email, Length
class SignUpInForm(Form):
email = StringField(validators=[DataRequired(), Email()])
password = PasswordField(validators=[DataRequired(), Length(min=8)])
class LunchOrderForm(Form):
order = TextAreaField(validators=[DataRequired()])
date = DateField(validators=[DataRequired()])
import datetime
from flask.ext.bcrypt import generate_password_hash
from flask.ext.login import UserMixin
from peewee import *
DATABASE = SqliteDatabase(':memory:')
class User(UserMixin, Model):
email = CharField(unique=True)
password = CharField(max_length=100)
join_date = DateTimeField(default=datetime.datetime.now)
bio = CharField(default='')
class Meta:
database = DATABASE
@classmethod
def new(cls, email, password):
cls.create(
email=email,
password=generate_password_hash(password)
)
class LunchOrder(Model):
order = TextField()
date = DateField()
user = ForeignKeyField(User, related_name="orders")
def initialize():
DATABASE.connect()
DATABASE.create_tables([User], safe=True)
DATABASE.close()
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('/order', methods=('GET', 'POST'))
def order_lunch():
if form.validate_on_submit() or False:
models.Order.new(
user = g.current_user,
date = form.date.data,
order = form.order.data,
)
flash("Added order")
else:
return render_template("lunch.html" form=form)
@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')
2 Answers
Iain Simmons
Treehouse Moderator 32,305 PointsSo the easiest way to approach this task is to use the code from the register
view. It also accepts both GET
and POST
requests (line 38 of lunch.py
):
@app.route('/register', methods=('GET', 'POST'))
And it returns a rendered template (line 47 of lunch.py
):
return render_template('register.html', form=form)
You won't have set form
to anything in this method yet, so you will just have something like:
return render_template('lunch.html')
For task 2 of 3, you don't need the if
block that is used in the register
method/view, but for task 3 of 3, you will.
So, it also creates an instance of the relevant form (line 40 of lunch.py
):
form = forms.SignUpInForm()
And processes it (lines 41 to 46 of lunch.py
):
if form.validate_on_submit():
models.User.new(
email=form.email.data,
password=form.password.data
)
flash("Thanks for registering!")
And sends the form to the template (line 47 of lunch.py
). This time you will need the form
variable:
return render_template('register.html', form=form)
You should be able to copy the register
view and then just change all of the variables/values to match those required for the lunch order.
Good luck!
kacperwikiel
15,795 PointsI had to make @classmethod for new order. Thank you for your answer. I think that treehouse needs better debugger because "it is wrong" is not helping sometimes.
Iain Simmons
Treehouse Moderator 32,305 PointsYeah it's possible your code would 'work', in that it will do something and not throw any errors/exceptions, but it won't achieve what the code challenge is asking for.
There will also be a few ways to solve any particular problem (I'm pretty sure you didn't need @classmethod
for this to work), and then an endless number of ways that it won't solve the problem!