已有183人关注
关于《Python项目开发案例集锦》第17章后台商品添加/编辑功能页面子类下拉框提示“Not a valid choice”
发表在Python图书答疑 2019-10-31
是否精华
版块置顶:

问题页面:后台——商品添加/编辑功能页面;

发现问题:提交表单失败,子类下拉框提示“Not a valid choice”信息;

问题追踪:FlaskForm对于SelectField验证失败;

问题原因:表单提交的子类数据不存在于后台方法所定义的子类列表的数据中;

因此要对定义子类数据列表的代码进行修改;

原代码:

#路径:admin/views.py
def goods_add():
    ...
    form.subcat_id.choices = [(v.id, v.cat_name) for v in SubCat.query.filter_by(super_cat_id=supercat_list[0][0]).all()]  # 为super_cat_id添加属性
    ...
    
def goods_edit(id=None):
    ...
    form.subcat_id.choices = [(v.id, v.cat_name) for v in SubCat.query.filter_by(super_cat_id=goods.supercat_id).all()]  # 为super_cat_id添加属性
    ...

修正代码:

#路径:admin/views.py
def goods_add():
    ...
    if form.data['supercat_id']:
        form.subcat_id.choices=[(v.id,v.cat_name) for v in SubCat.query.filter_by(super_cat_id=int(form.data["supercat_id"])).all()]
    else:
        form.subcat_id.choices=[(v.id,v.cat_name) for v in SubCat.query.filter_by(super_cat_id=supercat_list[0][0]).all()]
    ...
    
def goods_edit(id=None):
    ...
    if form.data['supercat_id']:
        form.subcat_id.choices=[(v.id,v.cat_name) for v in SubCat.query.filter_by(super_cat_id=int(form.data['supercat_id'])).all()]    
    else:
        form.subcat_id.choices=[(v.id,v.cat_name) for v in SubCat.query.filter_by(super_cat_id=goods.supercat_id).all()]    # 为super_cat_id添加属性
    ...


分享到:
手机同步功能介绍
友情提示:以下图书配套资源能够实现手机同步功能
明日微信公众号
明日之星 明日之星编程特训营
客服热线(每日9:00-17:00)
400 675 1066
mingrisoft@mingrisoft.com
吉林省明日科技有限公司Copyright ©2007-2022,mingrisoft.com, All Rights Reserved长春市北湖科技开发区盛北大街3333号长春北湖科技园项目一期A10号楼四、五层
吉ICP备10002740号-2吉公网安备22010202000132经营性网站备案信息 营业执照