【问题标题】:Pass additional data via POST from django template submit通过 POST 从 django 模板提交传递附加数据
【发布时间】:2018-08-13 21:13:08
【问题描述】:

使用Django模板显示input text的表格。

但在view 中,只有来自该表的输入出现在request.POST 中。 POST 中不提供动态创建的输入。

test.html

<form class="form-horizontal" method="post" enctype='multipart/form-data' id="subscription-form">
....
....
<tbody class="draggable-column">
    {% for product in products %}
    <tr>
        <td class="hidden-xs">{{forloop.counter}}</td>
        <td class="hidden-xs">{{product.title}}</td>
        <td class="hidden-xs">{{product.weight}}</td>
        <td class="" >{{product.yearly_consumption}}</td>
        <td><input type="text" id="{{product.id}}_jan" data-id="{{product.id}}_jan" class="user-action"></td>
        <td><input type="text" id="{{product.id}}_feb" data-id="{{product.id}}_feb" class="user-action"></td>
        <td><input type="text" id="{{product.id}}_mar" data-id="{{product.id}}_mar" class="user-action"></td>
         ......
         ......
         <td><input type="text" id="{{product.id}}_total" data-id="{{product.id}}_total" readonly="readonly" class="total-quantity"></td>
     </tr>
     <input type="hidden" value="{{product.weight}}" id="{{product.id}}_weight">
     <input type="hidden" value="{{product.is_winter}}" id="{{product.id}}_winter">
     {% endfor %}
</tbody>
....
....
</form>

此表输入在 django 视图的 POST 中不可用。

如何在 POST 中提供此功能?

【问题讨论】:

  • 您的所有输入都没有name 属性,因此它们不会包含在POST 数据中。您需要为所有这些指定一个name 属性。

标签: django python-3.x django-templates django-views


【解决方案1】:

您需要向每个input tags 提及name attribute

<tr>
   <td class="hidden-xs">{{forloop.counter}}</td>
   <td class="hidden-xs">{{product.title}}</td>
   <td class="hidden-xs">{{product.weight}}</td>
   <td class="" >{{product.yearly_consumption}}</td>
   <td><input type="text" id="{{product.id}}_jan" data-id="{{product.id}}_jan" name="{{product.id}}_jan" class="user-action"></td>
   <td><input type="text" id="{{product.id}}_feb" data-id="{{product.id}}_feb" name="{{product.id}}_feb" class="user-action"></td>
   <td><input type="text" id="{{product.id}}_mar" data-id="{{product.id}}_mar" name="{{product.id}}_mar" class="user-action"></td>
   <td><input type="text" id="{{product.id}}_total" data-id="{{product.id}}_total" name= "{{product.id}}_total" readonly="readonly" class="total-quantity"></td>
 </tr>
     <input type="hidden" value="{{product.weight}}" id="{{product.id}}_weight" name="{{product.id}}_weight" >
     <input type="hidden" value="{{product.is_winter}}" id="{{product.id}}_winter" name="{{product.id}}_winter">
{% endfor %}

或输入您认为适合您目的的任何名称

【讨论】:

  • 谢谢你为我工作。如果有 10 个产品,我怎么能把这一切都放在 django 表单变量中?
  • 命名并添加一些动态值,或者为所有输入保持相同的名称,您将在 request.POST 中获取它们
  • 这个动态值如何以 djanfo 形式声明为表单变量。否则会执行无效的表单。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-03
  • 1970-01-01
相关资源
最近更新 更多