SelectField“无效的选择”

时间:2019-01-22 12:59:47

标签: python flask

无法使用带有烧瓶表单的SelectField创建新的“帖子”(研究)。

我正在尝试为我的网站提供“研究”应用程序。在“新研究”模板中,我从SelectField中收到一个错误“无效选择”。我设置了元组:     (id,标签) 与coerce = int。

我也尝试过元组,例如:     (“开幕”,“开幕”) 不强制= int。在这两种情况下,我都会遇到相同的错误

# forms.py:

from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, TextAreaField, SelectField
from wtforms.validators import DataRequired


choices = [(1, 'Opening'), (2, 'Middlegame'), (3, 'Endgame'), (4, 'Match')]

class StudyForm(FlaskForm):
    title = StringField('Title', validators=[DataRequired()])
    content = TextAreaField('Content', validators=[DataRequired()])
    category = SelectField('Category', choices = choices, validators = [DataRequired()], coerce=int)
    board = StringField('Embeded board', validators=[DataRequired()])

    submit = SubmitField('Add game')



# models.py
class Study(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    title = db.Column(db.String(100), nullable = False)
    content = db.Column(db.Text, nullable = False)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable = False)
    board = db.Column(db.String(100), nullable = False)
    category = db.Column(db.Integer, nullable = False) #tried also with db.String(100) now I'm not sure which i should choose



# routes.py
@studies.route("/study/new", methods=['GET', 'POST'])
@login_required
def new_study():
    form = StudyForm()
    if form.validate_on_submit():

        study = Study(title=form.title.data, content=form.content.data, user_id=current_user, board=form.board.data, category=form.category.data)
        db.session.add(study)
        db.session.commit()
        flash('Your study has been created!', 'success')
        return redirect(url_for('main.home'))
    return render_template('create_study.html', title='New Study',
                           form=form, legend='New Study')


#create_study.html
{{ form.category.label(class="form-control-label") }}
<select class="custom-select custom-select-lg mb-3" id=category name=category>

<option value="1">Opening</option>
<option value="2" selected>Middlegame</option>
<option value="3">Endgame</option>
<option value="4">Match</option>
</select>

0 个答案:

没有答案