Python代码:( main _
...
from flask import Flask, render_template, url_for,request,flash,redirect
from formzxc import Amount
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SECRET_KEY'] = '8ed085d7c0aefb62c65e9d2154c3f377'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///testing.db'
app.config['SQLALCHEMY_ECHO'] = True
db = SQLAlchemy(app)
class Category(db.Model):
id = db.Column(db.Integer,primary_key = True)
desc = db.Column(db.String(25),unique = True,nullable =False)
amt = db.Column(db.Integer,nullable =False)
def __repr__(self):
return f"Category('{self.desc}'.'{self.amt}')"
@app.route('/',methods = ['GET','POST']) #need to research more on the methods
@app.route('/main',methods = ['GET','POST'])
def home():
form = Amount() #this is the amount FlaskForm imported
if form.validate_on_submit(): #validation is true
flash(f'Done liao','success') #a message to put; put at homepage or prev page
newpost = Category(desc = Amount.purpose.data,amt =Amount.amount.data ) ##
db.session.add(newpost)
db.session.commit()
return redirect(url_for('home')) #function
else:
flash('Shit!','danger')
return render_template(f'test.html',form = form)
if __name__ == '__main__':
app.run(debug=True)
....
Python代码(对于formzxc) 从flask_wtf导入FlaskForm 从wtforms导入StringField,PasswordField,SubmitField,BooleanField,IntegerField 从wtforms.validators中导入DataRequired,Length,Email,EqualTo
class Amount(FlaskForm):
purpose = StringField('Type:',
validators = [DataRequired(),Length(max =25)])
amount = IntegerField('Amount:',
validators = [DataRequired()])
submit = SubmitField('Submit!')
答案 0 :(得分:0)
修正波纹管错误
newpost = Category(desc = Amount.purpose.data,amt =Amount.amount.data )
更改为
newpost = Category(desc = form.purpose.data,amt =form.amount.data )
因为您在创建FlaskForm对象时将其传递给Amount类,所以Amount类继承了它的对象形式。因此,您必须使用该对象来获取数据。