我是Python和Flask的新手。我尝试创建一个网站,您可以在其中添加书籍并将其写入MySQL数据库。当我使用PyCharm运行我的项目时它工作正常,直到我导航到我想要添加我的书籍的网站。 错误说:NameError:全局名称'表格'没有定义。 有人可以帮我解决这个问题吗?也许我把代码写在错误的地方,我不知道。
我的代码是:
views.py:
from flask import render_template, flash, redirect, session, url_for, request
from flask.ext.login import login_user, logout_user, current_user, login_required
from app import app, db, mysql
from .forms import LoginForm, AddForm, RegForm
from .models import User
@app.route('/books/add/admin', methods=['GET', 'POST'])
def books_add_admin():
add = AddForm()
if request.method == 'POST':
cursor = mysql.connect().cursor()
'''
cursor = mysql.get_db().cursor()
author = request.args.get(form.author.data)
'''
test = request.args.get(form.title.data)
author = request.args.get(form.author.data)
verlag = request.args.get(form.publisher.data)
isbn = request.args.get(form.isbn.data)
auflage = request.args.get(form.edition.data)
exemplare = request.args.get(form.copies.data)
kurztext = request.args.get(form.short_text.data)
cursor.execute("INSERT INTO books (Titel, Autor, Verlag, ISBN, Auflage, Info)
VALUES (titel, author, verlag, isbn, auflage, info);")
#cursor = mysql.connect().cursor()
con.commit()
curser.close()
和forms.py的代码:
from flask.ext.wtf import Form
from wtforms import StringField, IntegerField, BooleanField, PasswordField, validators,
TextAreaField
from wtforms.validators import DataRequired, Length
class LoginForm(Form):
student_number = IntegerField('student_number', validators=[DataRequired()])
password = PasswordField('password', validators=[DataRequired()])
#remember_me = BooleanField('remember_me', default=False)
class AddForm(Form):
title = StringField('title', validators=[DataRequired()])
author = StringField('author', validators=[DataRequired()])
publisher = StringField('publisher', validators=[DataRequired()])
isbn = IntegerField('isbn', validators=[Length(min=10, max=13)])
edition = IntegerField('edition', validators=[Length(min=1, max=3)])
copies = IntegerField('copies', validators=[Length(min=1, max=3)])
short_info = TextAreaField('short_info', validators=[Length(min=0, max=1040)])
class RegForm(Form):
student_number = IntegerField('student_number', validators=[Length(min=6, max=7)])
forname = StringField('forname', validators=[DataRequired()])
surname = StringField('surname', validators=[DataRequired()])
email = StringField('email', validators=[DataRequired()])
password = PasswordField('password', validators=[Length(min=6, max=24)])
password2 = PasswordField('password2', validators=[Length(min=6, max=24)])
答案 0 :(得分:3)
在views.py中,尝试更改:
add = AddForm()
要
form = AddForm()
答案 1 :(得分:3)
这似乎是个问题:
add = AddForm()
您将变量命名为add
,而您正在尝试在此处引用变量form
:
test = request.args.get(form.title.data)
author = request.args.get(form.author.data)
verlag = request.args.get(form.publisher.data)
isbn = request.args.get(form.isbn.data)
auflage = request.args.get(form.edition.data)
exemplare = request.args.get(form.copies.data)
最简单的解决方案是重命名变量:
form = AddForm()