使用Flask,WTForm,SQLAlchemy和Jinja2的完整多对一示例

时间:2014-04-08 05:27:21

标签: python flask flask-sqlalchemy wtforms flask-wtforms

这是我的HTML下拉菜单。该值是子表的主键。

<select id="category" name="category">
   <option selected value="__None"></option>
   <option value="1">Category Number One</option>
   <option value="2">Category Number Two</option>
</select>

我需要使用值整数1而不是“类别编号一”更新Post.category_id。这是我的代码。

# create new post
@app.route('/admin/post', methods=['GET', 'POST'])
@login_required # Required for Flask-Security
def create_post():
    form = PostForm()
    if form.validate_on_submit():
        post = Post(title=form.title.data,
                    body=form.body.data,
                    pub_date=form.pub_date.data,
                    cateogry_id=form.category.data)
        db.session.add(post)
        db.session.commit()
        flash('Your post has been published.')
        return redirect(url_for('admin'))
    posts = Post.query.all()
    return render_template('create_post.html', form=form, posts=posts)

我试过制作......

cateogry_id=form.category.data
cateogry_id=form.category.value

现在不会那么好!

1 个答案:

答案 0 :(得分:7)

我明白了!这是我的解决方案。希望这篇文章能够帮助下一个人。

解决方案是让扩展为您完成工作!下面是使用Flask,WTForm,SQLAlchemy和Jinja2的WT Forms sqlalchemy扩展的工作示例。简而言之,您不必担心子ID,因为扩展会自动处理它。这意味着当您在一对多关系中处理SQLAlchemy父子模型时,您只需处理PARENT。

MODEL

首先,确保您的模型和关系正确无误。请注意我的示例中如何定义关系以及模型的 init 仅具有CATEGORY ... NOT CATEGORY_ID。我的错误是认为我会填充我的模型的CATEGORY_ID字段。不。扩展程序适合您。事实上,如果你尝试像我一样手动完成它将无法正常工作....

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(80))
    url = db.Column(db.String(120))
    body = db.Column(db.Text)
    create_date = db.Column(db.DateTime)
    pub_date = db.Column(db.DateTime)
    pub_status = db.Column(db.Text(80))
    author_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    author = db.relationship('User',
                             backref=db.backref('posts', lazy='dynamic'))
    category_id = db.Column(db.Integer, db.ForeignKey('category.id'))
    category = db.relationship('Category',
                               backref=db.backref('posts', lazy='dynamic'))

    def __init__(self, title, body, category, pub_date=None):
        self.title = title
        self.body = body
        if pub_date is None:
            pub_date = datetime.utcnow()
        self.category = category
        self.pub_date = pub_date

    def __repr__(self):
        return '<Post %r>' % self.title

class Category(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))
    description = db.Column(db.String(250))

    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return self.name

其次,查看表单....注意我正在使用wtfrom sqlalchmey QuerySelectedField并且Category_ID字段不存在...

FORM

from sprucepress.models import Tag, Category
from flask_wtf import Form
from wtforms.fields import StringField, DateTimeField
from wtforms.widgets import TextArea
from wtforms.validators import DataRequired
from wtforms.ext.sqlalchemy.orm import model_form
from wtforms.ext.sqlalchemy.fields import QuerySelectField


def enabled_categories():
    return Category.query.all()


class PostForm(Form):
    title = StringField(u'title', validators=[DataRequired()])
    body = StringField(u'Text', widget=TextArea())
    pub_date = DateTimeField(u'date create')
    category = QuerySelectField(query_factory=enabled_categories,
                                allow_blank=True)

现在FLASK路由和视图逻辑...再次在帖子NO category_id中注意!只有类别!!!

ROUTING / VIEW

# create new post
@app.route('/admin/post', methods=['GET', 'POST'])
@login_required  # required for Flask-Security
def create_post():
    form = PostForm()
    if form.validate_on_submit():
        post = Post(title=form.title.data, pub_date=form.pub_date.data,
                    body=form.body.data, category=form.category.data)
        db.session.add(post)
        db.session.commit()
        flash('Your post has been published.')
        return redirect(url_for('admin'))
    posts = Post.query.all()
    return render_template('create_post.html', form=form, posts=posts)

最后,模板。猜猜看,我们只生成form.category字段!!!

TEMPLATE

  <form action="" method=post>
  {{form.hidden_tag()}}
    <dl>
      <dt>Title:
      <dd>{{ form.title }}
      <dt>Post:
      <dd>{{ form.body(cols="35", rows="20") }}
      <dt>Category:
      <dd>{{ form.category }}

    </dl>
    <p>
      <input type=submit value="Publish">
  </form>

结果...此解决方案正确地使用Category模型作为查找表,并通过将Category PK整数写入Posts Category_Id字段来正确关联Post行。 Yeeeehaww!