【发布时间】:2020-04-09 21:50:00
【问题描述】:
我开始使用 Flask 并尝试创建一个简单的数据库 Web 应用程序。
它呈现 2 个 html 模板:
-
show_all.html显示一个数据库表的数据 -
new.html是向表格中插入数据的表单
show_all.html 正确呈现。当我单击new.html 上的提交按钮时,我收到以下错误消息:
TypeError: __init__() takes 1 positional argument but 2 were given
app.py
from flask import Flask, request, flash, url_for, redirect, render_template
from flask_sqlalchemy import SQLAlchemy
import psycopg2
DB_URL = 'postgresql+psycopg2://{user}:{pw}@{url}/{db}'.format(user='*******',pw='******',url='******',db='*****')
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = DB_URL
db = SQLAlchemy(app)
class test (db.Model):
__table_args__ = {"schema":"SaubannerDB"}
id1 = db.Column('id1', db.Integer, primary_key=True)
name1 = db.Column(db.String(10))
def __init__(self, name1, id1):
self.name1 = name1
self.id1 = id1
@app.route('/')
def show_all():
return render_template ('show_all.html', tests=test.query.all())
@app.route('/new', methods=['GET','POST'])
def new():
if request.method == 'POST':
if not request.form['name1'] or not request.form['id1']:
flash ('Please enter all fields')
else:
name1 = test(request.form['name1'])
id1 = test(request.form['id1'])
entry = (name1,id1)
db.session.add(entry)
db.session.commit()
return render_template('new.html')
return render_template('new.html')
app.run(host = '0.0.0.0', port = 5050)
app.debug = True`
new.html 文件如下所示:
<!DOCTYPE html>
<html>
<body>
<form method="post" action="/new">
<label for="name1"/label><br>
<input type="text" name="name1" placeholder="name"><br>
<label for="id1"/label><br>
<input type="text" name="id1" placeholder="id"><br>
<input type="submit" value="Submit"><br>
</form>
</body>
</html>`
有人可以帮忙吗?
【问题讨论】:
-
为什么你的
__init__()方法在类之外?
标签: python html postgresql flask