【问题标题】:Django - local variable 'secs' referenced before assignmentDjango - 分配前引用的局部变量'secs'
【发布时间】:2017-07-17 21:56:01
【问题描述】:

我一直在努力解决这个问题,但我不知道如何

我有一个表格,我收到secs

form role="form" action="" method="POST" >{% csrf_token %}
          <br>
          <input type="number" name="secs" min="0" max="999" maxlength="3" class="form-control no-spinners" placeholder="Programar...">
          <br>
          <button type="submit" id="btn-login" class="w3-btn w3-large w3-green" style="width:30%"> Aceptar </button>
        </form> 

在我的 views.py

def streaming(request):
    if request.method == 'POST':
        secs = request.POST['secs']
        print secs
        programarTiempo(secs)
        messages.info(request, 'Iniciando streaming en...' + secs + ' segundos')
        time.sleep(float(secs))
        return redirect('streaming')
    return render(request, "straming.html", {"secs":secs})

当我访问我的 .html 时,出现以下错误:

UnboundLocalError 在 /streaming/ 局部变量 'secs' 被引用 分配前

提前致谢!

【问题讨论】:

  • 如果 request.method 不是“POST”,则永远不会定义 secs,因此当您尝试调用 render() 时,会出现错误。
  • 是的,我知道那部分,但如果我在 post 方法之外定义 secs,我将无法获得 secs 的正确值
  • 您从 request.POST['secs'] 获取值,当 request.method 不是 POST 时,该值不存在。所以我不知道你可能期望得到什么价值......
  • 你想要 previous 函数执行的secs 的值吗?
  • 如果请求是 GET,请尝试在查询字符串中接受它。像这样 /my/app/myroute?secs=3。然后在您的控制器中,您可以拥有sec = request.args["secs"]

标签: python html django


【解决方案1】:

问题是如果方法不是 Post,它会返回(最后一行),它有 secs 变量,但你在 if 条件中定义了它

【讨论】:

    猜你喜欢
    • 2021-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-20
    相关资源
    最近更新 更多