我试图创建一个包含两个链接表Info和User的数据库,我也希望能够在我在我的索引页面上单击提交后运行下面的代码时在线发布到数据库,我收到一个错误:'该方法不允许用于请求的URL。',并且没有任何内容发布到我的数据库中。我是python和SQLAlchemy的新手,所以我不确定错误发生在哪里。这是我的python代码:
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import relationship, backref, sessionmaker
from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.ext.declarative import declarative_base
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:////Users/me/attempt1/attempt.db"
app.debug = True
db = SQLAlchemy(app)
engine = create_engine('sqlite:////Users/me/attempt1/attempt.db')
connection = engine.connect()
Base = declarative_base()
session = sessionmaker(bind=engine)
class Info(Base):
__tablename__ = 'info'
id = Column(Integer, primary_key=True)
username = Column(String(80), unique=True, nullable=False)
age = Column(Integer, nullable=False)
country = Column(String(120), nullable=False)
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
email = Column(String(225), unique=True, nullable=False)
username = relationship('Info', backref=backref('users', lazy='True'))
password = Column(String(225), nullable=False)
# this will be the home page
Base.metadata.create_all(engine)
session = session()
@app.route('/')
def index():
return render_template('dashboard.html')
# sign up page
@app.route('/signup', methods=['POST'])
def signup():
info = Info(request.form['username'], request.form['age'], request.form['country'])
user = User(request.form['email'], request.form['password'])
session.add(info)
session.add(user)
session.commit()
return redirect(url_for('login'))
@app.route('/login')
def login():
return 'You are now logged in'
if __name__ == '__main__':
app.run()
这是我的dashboard.html的html代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sign Up Today</title>
</head>
<body>
<form method ="signup" action="/signup">
<label>Email:</label>
<input id="email" name="email" type="text"/>
<label>Username:</label>
<input id="username" name="'username" type="text"/>
<label>Password:</label>
<input id="password" name="password" type="'text"/>
<label>Age:</label>
<input id="'age" name="age" type="text"/>
<label>Country:</label>
<input id="country" name="country" type="text"/>
<input type="submit"/>
</form>
</body>
</html>
答案 0 :(得分:1)
您的表单方法应该是“发布”。
<form method="post" action="/signup">
答案 1 :(得分:0)
让你的方法在模板中发布
<form method="post" action="/signup">
<!-- -->
</form>
你也忘了创建表单。
class UserForm(Form):
username = StringField("User Name")
age = IntegerField("Enter Age")
# add more fields
在视图中首先验证您的表单
@app.route('/signup', methods=['POST'])
def signup():
form = UserForm()
if form.validate_on_submit():
user_data = {
username = form.username.data,
age = form.age.data,
# so on
}
session.add(user_data)
session.commit()
return redirect(url_for('login'))
return render_template('dashboard.html', form=form)