Python Flask将表单数据保存到DB

时间:2016-02-29 16:13:47

标签: python flask-sqlalchemy

我是Flask的新手,我正在尝试使用SQLAlchemy将表单数据从Flask表单保存到数据库,我没有运气。我在本论坛的这里和外面都发现了一些研究方法。

当我采用简单化的路线时,网络表单可以工作,我可以输入数据,但不会填充数据库。

---- ----模型

class QIDMapping(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    qid_number = db.Column(db.Integer)
    br_field_name = db.Column(db.String(75))
    vendor_field = db.Column(db.String(75))

---- ----表格

class QIDForm(Form):
    qidnumber = IntegerField('qidnumber', validators=[DataRequired()])
    brfieldname = StringField('brfieldname', validators=[DataRequired()])
    vendorfieldname = StringField('vendorfieldname')

---- ----浏览

from flask import render_template, flash, redirect, session, url_for, 
request, g
from flask_wtf import form
from app import app, db
from .forms import QIDForm
from .models import User, QIDMapping
from flask.ext.sqlalchemy import SQLAlchemy


@app.route('/qidmapping', methods=['GET', 'POST'])
def qid_map_update():
    form = QIDForm()
    return render_template('qidmapping.html',
                            title='QID Mapping',
                            form=form)

---- ---- qidmapping.html

{% block content %}

    <h1>Map QIDs to Vendor File</h1>
    <form action="" method="POST">
        {{form.hidden_tag()}}
        <p>
            Please enter the QID, BrassRing Field Name and Vendor Tag
            <br>
            <h2>QID Number {{ form.qidnumber(size=25) }}<br></h2>
            <h2>BR Field   {{ form.brfieldname(size=25) }}<br></h2>
            <h2>Vendor Field   {{ form.vendorfieldname(size=25) }}<br></h2>
        </p>
        <p><br>
        </p>
        <p><input type="submit" value="Save Fields">
        </p>
    </form>
{% endblock %}

我也试过这篇文章Flask - WTForm - save form to db中的方法 当我这样做时,我得到一个方法不允许的错误,我不知道为什么。

----查看问题20837209格式----

@app.route('/qidmapping', methods=['GET', 'POST'])
def qid_map_update():
    form = QIDForm()
    if form.validate_on_submit():
        newform = (
            form.qidnumber.data,
            form.brfieldname.data,
            form.vendorfieldname.data
            )
        db.session.add(newform)
        db.session.commit()
        return redirect('/qidmapping')
    return render_template('qidmapping.html',
                            title='QID Mapping',
                            form=form)

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

尝试替换

newform = (
            form.qidnumber.data,
            form.brfieldname.data,
            form.vendorfieldname.data
            )
db.session.add(newform)

m = QIDMapping()
m.qid_number = form.qidnumber.data
m.br_field_name = form.brfieldname.data
m.vendor_field = form.vendorfieldname.data
db.session.add(m)

......如果那不起作用。做标准的POST故障排除:

1)验证POST请求

2)确保CSRF正常运行。

3)记录验证错误/成功

4)检查数据库异常