【问题标题】:Django passing a variable to Httpresponseredirect throws exceptionDjango 将变量传递给 Httpresponseredirect 引发异常
【发布时间】:2016-09-06 00:56:22
【问题描述】:

我现在遇到的问题是:

未找到带有参数“(1,)”和关键字参数“{}”的“文档”的反向操作。尝试了 0 个模式:[]

当我尝试使用 HttpResponseRedirect 重定向到另一个视图时

这是我的 urls.py

    url(r'^documentation/([0-9])/$', views.documents, name='documentation'),

这里是我的意见.py

def view1(request):

  if request.method == 'POST':
      profe = request.POST.get('value')

      a = value.encode('ascii', 'ignore')
      b = int(a)
      return HttpResponseRedirect(reverse('documentation', args=(b,)))

  else:

      return render(request, "anhtml.html", info)

def documents(request,valor):
      ...something...
      return render(request, "anotherhtml.html", ..something..)

谢谢

模板(anhtml.html)

...
    <form method="POST" action="">
        {% csrf_token %}
        {% for p in ps %}
        <tr>
            <td><button id="boton1" button type="submit" name = "valor" value ="{{p.idp}}" class="btn btn-success btn-sm">{{p.nombre}} {{p.apellido}}</button>
            </td>
            <td>algo</a> </td>
        </tr>
        {%endfor%}
    </form>

【问题讨论】:

  • 出现错误时您尝试访问的 url 是什么?
  • 主要想法是我被重定向到127.0.0.1:8000/documentation/1,但事实并非如此。如果将该网址直接粘贴到浏览器中,我将成功重定向。所以我现在确定正则表达式可以正常工作
  • 什么动作触发了错误?显示您的模板代码可能会有所帮助。
  • 刚刚添加了我的模板表单,实际上并没有比这复杂多少

标签: python django


【解决方案1】:

我认为问题不在于 HttpResponseRedirect,而在于对 reverse() 的调用。

当你传递参数时,你应该为值使用列表符号:

return HttpResponseRedirect(reverse('documentation', args=[b]))

至少应该有帮助。

【讨论】:

  • 对于 1 项列表,您不需要 ,。此外,OP 尝试这个也不会受到伤害,但我一直使用元组而不是列表来处理 args 参数没有问题。
  • 感谢您的回答,不幸的是,这并没有成功,但仍然很有帮助。
【解决方案2】:

我认为你应该为你的观点添加论据

只是改变

def view1(请求):

def view1(request, p):

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 2014-01-12
  • 2023-03-15
  • 2014-05-05
  • 2011-10-01
  • 2016-12-28
  • 2019-03-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多