【问题标题】:POST data has wrong value for Django template variable?Django 模板变量的 POST 数据值错误?
【发布时间】:2010-11-23 08:58:28
【问题描述】:

我的模板中有以下代码:

<form action="" method="post">{% csrf_token %}  
    {%for category, category_votes in votes%}  
        <p>{{category}}: {{category_votes}} <!-- displays as expected -->  
            <input type="hidden" name="votedCat" value="{{category}}" id={{forloop.counter}}>  
            <input type="submit" name="upvote" value="Vote for...">  
            <input type="submit" name="downvote" value="Vote against...">  
        </p>  
    {%endfor%}  
</form>

变量{{category}} 在渲染时按预期显示,但查看POST 数据,"votedCat" 始终是votes 中的最后一个category 值。

例如,如果votes=[('a',1),('b',2),('c',3)],则无论使用哪个输入按钮提交表单,request.POST['votedCat'] 都会返回'c'。我做错了什么?

【问题讨论】:

    标签: python django django-templates


    【解决方案1】:

    因为您只有一个表单,votedCat 有多个输入。点击任何按钮提交整个表单,all是votedCat的值。如果您要访问request.POST.getlist('votedCat'),您会发现您实际上拥有所有值。

    有两种方法可以解决此问题。第一个是循环中的每次迭代都有单独的表单元素 - 为此,只需在循环内移动 &lt;form&gt; 和 &lt;/form&gt; 元素。

    第二个是让votedCat 输入实际上是提交按钮:

    <input type="submit" name="votedCat" value="Vote for {{category}}" id={{forloop.counter}}>
    

    这里的缺点是现在您的变量中有“投票”字样,您需要在视图代码中解析出来。

    设置一个简单的单选按钮或带有单个提交按钮的选择框比这两种方法更好,但我知道设计要求有时会妨碍您。

    最后,您应该真正使用 Django 的表单框架,而不是使用手动 HTML 并直接处理 POST。

    【讨论】:

    • 啊,有道理。我会将表单放入循环中。也不知道 .getlist() 方法。谢谢!
    【解决方案2】:

    我不确定这是否是最佳解决方案,但您可以在循环内创建一个新的form:

    {%for category, category_votes in votes%}  
        <p>{{category}}: {{category_votes}} <!-- displays as expected -->  
        <form action="" method="post">{% csrf_token %}  
            <input type="hidden" name="votedCat" value="{{category}}" id={{forloop.counter}}>  
            <input type="submit" name="upvote" value="Vote for...">  
            <input type="submit" name="downvote" value="Vote against...">
        </form>
        </p>  
    {%endfor%}  
    

    您可以考虑使用django.forms.Form 类来构建和处理您的表单。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-18
      • 2012-01-29
      • 2012-07-04
      • 1970-01-01
      • 2023-04-03
      • 2010-10-07
      • 2017-10-01
      • 1970-01-01
      相关资源
      最近更新 更多