【问题标题】:Jinja2/Flask, I Can't get a dynamic value from a checkboxJinja2/Flask,我无法从复选框中获取动态值
【发布时间】:2020-05-25 02:30:33
【问题描述】:

所以我有这个html

<label class="continer">Empresa Confidencial
     {% if proyecto.10 == 1 %}
     <input type="checkbox" id="confidencial" name="confidencial" value="1" checked>
     {% else  %}
     <input type="checkbox" id="confidencial" name="confidencial" value="0">
     {% endif %}
     <span class="checkmark"></span>
</label>

项目.py

def editar_(confidencial,estado,id):
    cur = mysql.connection.cursor()
    cur.execute('UPDATE proyecto set EMPRESA_CONFIDENCIAL=%s,estado=%s where PK_PROYECTO=%s', (confidencial,estado, id,))
    mysql.connection.commit()

adminviews.py

@app.route("/editar", methods=["POST"])
def editar():
    print('.................................................................................')
    id = request.form['id']
    estado = request.form.get('estado') 
    confidencial = request.form.get('confidencial')
    print(id,str(estado), str(confidencial))
    pr.editar_(confidencial,estado,id)
    return redirect(url_for('empresasT'))

我需要获取值"1" 或"0" 将其发送到数据库,问题是当我运行代码时,在proyect.py 和adminvie.py 中没有"confidencial",它运行并在数据库中进行更改,但是当我再次尝试使用"confidencial" 并在checkbox 中进行更改时,如果选中该复选框并且我未选中它,则值为无,但如果我将其选中,则value 是默认值,控制台说该值为null,MySQLdb._exceptions.OperationalError: (1048, "Column 'EMPRESA_CONFIDENCIAL' cannot be null"),该进程在修改后没有从checkbox 获取值"1" 或"0",而是我的其他值像 id 和 estado 一样,我认为是 if 语句,我如何使用 if 语句从 html 中的 checkbox 获取值

【问题讨论】:

    标签: python web flask jinja2


    【解决方案1】:

    我认为您应该在两个复选框中添加选中。

    【讨论】:

    • 嗯,没有,因为我需要在更改时捕获值 1 或 0,但是当我运行它并使用按钮提交更改时,值设置为“无” ,但如果我不更改复选框,它将保持默认状态
    • 您是否重新启动了服务器并重新加载了页面,因为有时它不会更新并且您不需要值为 1 或 0,因为选中的值已经是布尔值
    • 是的,我重新启动服务器并使用 shift+f5 重新加载,我将尝试获取检查值,然后将其转换为 1 或 0,因为做数据库的人将其设置为 1或 0...
    【解决方案2】:

    正如我调查的那样,flask 将复选框视为与 django 相同,因此我在 adminviews.py 代码中添加了这一行

     if confidencial is None:
        confidencial = "0"
    

    使复选框总是关闭,值将是none,但为了实际使用,我在方法内部修改它

    【讨论】:

      猜你喜欢
      • 2014-05-16
      • 1970-01-01
      • 1970-01-01
      • 2018-09-10
      • 2015-10-29
      • 1970-01-01
      • 1970-01-01
      • 2021-06-17
      • 2021-07-01
      相关资源
      最近更新 更多