Browse Source

Chapter 4: Web forms with Flask-WTF (4a)

master
T. Meissner 6 years ago
parent
commit
1b2e37426b
3 changed files with 19 additions and 20 deletions
  1. +16
    -8
      hello.py
  2. +3
    -3
      templates/index.html
  3. +0
    -9
      templates/user.html

+ 16
- 8
hello.py View File

@ -1,15 +1,23 @@
from datetime import datetime
from flask import Flask, render_template
from flask_bootstrap import Bootstrap
from flask_moment import Moment
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired
app = Flask(__name__)
app.config['SECRET_KEY'] = 'hard to guess string'
bootstrap = Bootstrap(app)
moment = Moment(app)
class NameForm(FlaskForm):
name = StringField('What is your name?', validators=[DataRequired()])
submit = SubmitField('Submit')
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
@ -20,11 +28,11 @@ def internal_server_error(e):
return render_template('500.html'), 500
@app.route('/')
@app.route('/', methods=['GET', 'POST'])
def index():
return render_template('index.html', current_time=datetime.utcnow())
@app.route('/user/<name>')
def user(name):
return render_template('user.html', name=name)
name = None
form = NameForm()
if form.validate_on_submit():
name = form.name.data
form.name.data = ''
return render_template('index.html', form=form, name=name)

+ 3
- 3
templates/index.html View File

@ -1,11 +1,11 @@
{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}
{% block title %}Flasky{% endblock %}
{% block page_content %}
<div class="page-header">
<h1>Hello World!</h1>
<h1>Hello, {% if name %}{{ name }}{% else %}Stranger{% endif %}!</h1>
</div>
<p>The local date and time is {{ moment(current_time).format("MMMM Do YYYY, HH:mm:ss")}}.</p>
<p>That was {{ moment(current_time).fromNow(refresh=True) }}</p>
{{ wtf.quick_form(form) }}
{% endblock %}

+ 0
- 9
templates/user.html View File

@ -1,9 +0,0 @@
{% extends "base.html" %}
{% block title %}Flasky{% endblock %}
{% block page_content %}
<div class="page-header">
<h1>Hello, {{ name }}!</h1>
</div>
{% endblock %}

Loading…
Cancel
Save