flask_wtf SelectField(错误:选择无效)

时间:2019-03-13 12:54:09

标签: python-2.7 flask sqlalchemy flask-wtforms

我正在使用Python 2.7和 我已经搜索了hereherehere的解决方案 但他们都没有解决我的问题 我正在一个简单的项目(我的第一个项目)中,使用flask和带有2个表的sqlite数据库练习CRUD:

  1. 类别
  2. 物品

问题是:

当我加载页面时,表单正确显示,并且当我选择任何类别并提交时,表单在致电时给我一个错误

validate_on_submit()

无效选择,返回值为False

我这样定义表格:

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


class EditItemForm(FlaskForm):
    name = StringField(u'name', validators=[DataRequired()])
    description = TextAreaField("Description", validators=[
                                DataRequired()], render_kw={'rows': '7'})
    categories = SelectField(
        u'Categories', coerce=str, choices=[], validators=[DataRequired()])

    def set_choices(self, list_of_tuples=[]):
        self.categories.choices = list_of_tuples

这是编辑项目的功能:

@app.route('/category/<string:category_name>/<string:item_name>/edit/',
        methods=['GET', 'POST'])
def editItem(category_name, item_name):
    # get the category of the Item
    c = getCategory(category_name)

    # get the Item
    target_item = getItem(c, item_name)

    form = EditItemForm()

    # FIXME: Complete The process
    if request.method == 'POST':
        if form.validate_on_submit():
            # get selected category
            cat = dict(form.categories.choices).get(form.categories.data)
            targetCategory = getCategory(cat)

            # get identicals to avoid dublication
            identicals = getItemIdenticalsInCategory(
                targetCategory, form.name.data)

            if len(identicals >= 1):
                # FIXME: flash the Error in the same page
                return "An Item with the same name " + form.name.data + "     already exists in " + targetCategory.name

            else:
                # Edit The Item Data
                target_item.name = form.name.data
                target_item.description = form.description.data
                target_item.category_id = targetCategory.id

                # TODO: Flash the response
                return redirect(url_for('readCategoryItems',
                                        category_name=category_name))

        else:
            # display errors
            output = ""
            for fieldName, errorMessages in form.errors.items():
                for err in errorMessages:
                    # do something with your errorMessages for fieldName
                    output += fieldName + ":\t" + err + "<hr>"
            print(output)
            return output

    if request.method == 'GET':

        # Populate The form with current data
        form.name.data = target_item.name
        form.description.data = target_item.description
        cats = getAllCategories()
        list_of_tupels = []

        for cat in cats:
            session.refresh(cat)
            list_of_tupels.append((cat.name, cat.name))

        form.set_choices(list_of_tuples=list_of_tupels)

        return render_template('updateItem.html', 
            category_name=category_name,
                            item_name=item_name, form=form)

这是错误输出:

categories: Not a valid choice<hr>

编辑: *这是我尝试调试时得到的: Debug Variables Screenshot

0 个答案:

没有答案