使用SQLAlchemy设置Bootstrap表单

时间:2017-11-11 12:53:04

标签: python twitter-bootstrap sqlite flask flask-sqlalchemy

我正在尝试使用我的Python Flask Web应用程序使用Bootstrap Forms,但我很难按照我想要的方式工作。

当前设置为当用户注册时,使用SQLAlchemy和SQLite3将其详细信息存储在数据库中。它目前似乎没有这样做。

最初我使用flask_bootstrap进行了代码设置,但我更喜欢使用本地引导程序文件,而不是我将在静态文件夹中找到的文件。

我已经包含了我原来使用的原始文件,这些文件是原始的app.py和原始的signup.html。我还包括了我一直在尝试创建的新文件,它们是新的app.py和新的signup.htm,以帮助重现这个应用程序。提前谢谢!

原始app.py文件

from flask import Flask, render_template, redirect, url_for
from flask_bootstrap import Bootstrap
from flask_wtf import FlaskForm 
from wtforms import StringField, PasswordField, BooleanField
from wtforms.validators import InputRequired, Email, Length
from flask_sqlalchemy  import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user

app = Flask(__name__)
app.config['SECRET_KEY'] = 'Thisissupposedtobesecret!'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////Users/Joanna/Desktop/login2/database.db'
Bootstrap(app)
db = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(15), unique=True)
    email = db.Column(db.String(50), unique=True)
    password = db.Column(db.String(80))

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

class LoginForm(FlaskForm):
    username = StringField('username', validators=[InputRequired(), Length(min=4, max=15)])
    password = PasswordField('password', validators=[InputRequired(), Length(min=8, max=80)])
    remember = BooleanField('remember me')

class RegisterForm(FlaskForm):
    email = StringField('email', validators=[InputRequired(), Email(message='Invalid email'), Length(max=50)])
    username = StringField('username', validators=[InputRequired(), Length(min=4, max=15)])
    password = PasswordField('password', validators=[InputRequired(), Length(min=8, max=80)])

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()

    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user:
            if check_password_hash(user.password, form.password.data):
                login_user(user, remember=form.remember.data)
                return redirect(url_for('dashboard'))

        return '<h1>Invalid username or password</h1>'
        #return '<h1>' + form.username.data + ' ' + form.password.data + '</h1>'

    return render_template('login.html', form=form)

@app.route('/signup', methods=['GET', 'POST'])
def signup():
    form = RegisterForm()

    if form.validate_on_submit():
        hashed_password = generate_password_hash(form.password.data, method='sha256')
        new_user = User(username=form.username.data, email=form.email.data, password=hashed_password)
        db.session.add(new_user)
        db.session.commit()

        return '<h1>New user has been created!</h1>'
        #return '<h1>' + form.username.data + ' ' + form.email.data + ' ' + form.password.data + '</h1>'

    return render_template('signup.html', form=form)

@app.route('/dashboard')
@login_required
def dashboard():
    return render_template('dashboard.html', name=current_user.username)

@app.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('index'))

if __name__ == '__main__':
    app.run('0.0.0.0', debug=True)

新的app.py文件

from flask import Flask, render_template, redirect, url_for
from flask_wtf import FlaskForm 
from wtforms import StringField, PasswordField, BooleanField
from wtforms.validators import InputRequired, Email, Length
from flask_sqlalchemy  import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user

app = Flask(__name__)
app.config['SECRET_KEY'] = 'Thisissupposedtobesecret!'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////Users/Joanna/Desktop/login2/database.db'
Bootstrap(app)
db = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(15), unique=True)
    email = db.Column(db.String(50), unique=True)
    password = db.Column(db.String(80))

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

class LoginForm(FlaskForm):
    username = StringField('username', validators=[InputRequired(), Length(min=4, max=15)])
    password = PasswordField('password', validators=[InputRequired(), Length(min=8, max=80)])
    remember = BooleanField('remember me')

class RegisterForm(FlaskForm):
    email = StringField('email', validators=[InputRequired(), Email(message='Invalid email'), Length(max=50)])
    username = StringField('username', validators=[InputRequired(), Length(min=4, max=15)])
    password = PasswordField('password', validators=[InputRequired(), Length(min=8, max=80)])

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()

    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user:
            if check_password_hash(user.password, form.password.data):
                login_user(user, remember=form.remember.data)
                return redirect(url_for('dashboard'))

        return '<h1>Invalid username or password</h1>'
        #return '<h1>' + form.username.data + ' ' + form.password.data + '</h1>'

    return render_template('login.html', form=form)

@app.route('/signup', methods=['GET', 'POST'])
def signup():
    form = RegisterForm()

    if form.validate_on_submit():
        hashed_password = generate_password_hash(form.password.data, method='sha256')
        new_user = User(username=form.username.data, email=form.email.data, password=hashed_password)
        db.session.add(new_user)
        db.session.commit()

        return '<h1>New user has been created!</h1>'
        #return '<h1>' + form.username.data + ' ' + form.email.data + ' ' + form.password.data + '</h1>'

    return render_template('signup.html', form=form)

@app.route('/dashboard')
@login_required
def dashboard():
    return render_template('dashboard.html', name=current_user.username)

@app.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('index'))

if __name__ == '__main__':
    app.run('0.0.0.0', debug=True)

原始signup.html模板

{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}

{% block title %}
Sign Up
{% endblock %}

{% block styles %}
{{super()}}
<link rel="stylesheet" href="{{url_for('.static', filename='signin.css')}}">
{% endblock %}

{% block body_content %}
<div class="container">

  <form class="form-signin" method="POST" action="/signup">
    <h2 class="form-signin-heading">Sign Up</h2>
    {{ form.hidden_tag() }}
    {{ wtf.form_field(form.username) }}
    {{ wtf.form_field(form.email) }}
    {{ wtf.form_field(form.password) }}
    <button class="btn btn-lg btn-primary btn-block" type="submit">Sign Up</button>
  </form>

</div> <!-- /container -->
{% endblock %}

新的signup.html模板

{% extends "base.html" %}

{% block title %}
Sign Up
{% endblock %}

<!-- Banner Image Content Begins -->
{% block img_content %}
    <div class="img_cont bg_img">
        <h1 class="banner">Sign Up</h1>
    </div>
{% endblock %}}
<!-- Banner Image Content Ends -->

{% block body_content %}
<div class="container">

<form method="POST" action="/signup">
    <div class="form-group">
        <input type="username" class="form-control" placeholder="Enter Username">{{ form.username }}</input>
    </div>
    <div class="form-group">  
        <input type="email" class="form-control" placeholder="Enter Email">{{ form.email }}</input>
    </div>
    <div class="form-group"> 
        <input type="password" class="form-control" placeholder="Enter Password">{{ form.password }}</input>
    </div>
  <button type="submit" class="btn btn-primary">Sign Up</button>
</form>

</div> <!-- /container -->


{% endblock %}

1 个答案:

答案 0 :(得分:0)

您似乎在 signup.html 中的表单中遗漏了{{ form.csrf_token }}

<form method="POST" action="/signup">
    {{ form.csrf_token }}
    <div class="form-group">

为了检测出现了什么问题,您可以在函数print(form.errors)中添加def signup():以在控制台中查看,或者甚至将其返回给用户的模板。

(模板在屏幕上呈现双input时有点奇怪,可能看看这个doc

修改

表单已经根据字段类型呈现输入标记,您只需要在模板中调用表单的字段。 (我刚刚添加了一个小循环来验证验证时的表单错误)

<div class="container">

<form method="POST" action="/signup">
    {{ form.csrf_token }}
    <div class="form-group">
       {{ form.username }}
    </div>
    <div class="form-group">
        {{ form.email }}
    </div>
    <div class="form-group">
        {{ form.password }}
    </div>
    <button type="submit" class="btn btn-primary">Sign Up</button>
    </form>

    {% for field, err in errors %}
      <div>{{field}} : {{err|join(', ')}}</div>
    {% endfor %}

</div> <!-- /container -->

要使错误循环起作用,只需在def signup():

中更改模板的return语句
return render_template('signup_bug.html', form=form, errors=form.errors.items())

现在,如果要定义占位符或其他属性,可以在特殊参数中传递它们:render_kw

class RegisterForm(FlaskForm):
    email = StringField('email', 
                        validators=[InputRequired(), Email(message='Invalid email'), Length(max=50)], 
                        render_kw={"placeholder": "Enter Email", "type":"email"})
    username = StringField('username', 
                           validators=[InputRequired(), Length(min=4, max=15)], 
                           render_kw={"placeholder": "Enter Username", "type":"username"})
    password = PasswordField('password', 
                             validators=[InputRequired(), Length(min=8, max=80)], 
                             render_kw={"placeholder": "Enter Password", "type":"password"})