簡體   English   中英

AttributeError: 'UnboundField' 對象沒有屬性 'data' (python Flask) 我們如何解決這個問題?

[英]AttributeError: 'UnboundField' object has no attribute 'data' (python Flask) How do we solve this?

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 代碼(for formzxc) from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField, BooleanField,IntegerField from wtforms.validators import DataRequired, Length, Email, EqualTo

class Amount(FlaskForm):
    purpose = StringField('Type:',
                          validators = [DataRequired(),Length(max =25)])
    amount = IntegerField('Amount:',
                          validators = [DataRequired()])
    submit = SubmitField('Submit!')

修復波紋管錯誤

newpost = Category(desc = Amount.purpose.data,amt =Amount.amount.data )

改成

newpost = Category(desc = form.purpose.data,amt =form.amount.data )

因為你在創建它時將 FlaskForm 對象傳遞給 Amount 類 Amount 類從它繼承了對象形式。所以你必須使用該對象來獲取數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM