【问题标题】:Edit a Model with an input. ValueError使用输入编辑模型。值错误
【发布时间】:2012-03-29 04:23:51
【问题描述】:

试图允许用户编辑十进制值“金额”。当用户单击“编辑”时,会显示一个小数字段。当用户完成更改值并单击“完成”时...

它会抛出这个错误:

Exception Type: ValueError Exception Value: Cannot use None as a query value

这是我的模板:

<form class="nice input-prepend edit-allocation-form" action="/portfolio/edit/" method="POST">
     {% csrf_token %}
     <input class="input-text required number" type="text" name="edit_amount{{ investment.position.id }}" {% if investment.position.amount %}value="{{ investment.position.amount }}"{% endif %}>

     <a href="#" class="edit" id="edit{{ investment.position.id }}">edit</a>
     <button class="hide" type="submit" id="saveAmountButton"></button>
</form> 

这是我的观点:

@login_required
def edit(request):
    if request.method == 'POST':
       profile = get_object_or_404(InvestorProfile, user=request.user)
       position = InvestorPosition.objects.filter(id__in=request.POST.get('id'))
       if Decimal(request.POST['edit_amount' + str(position.id)]) != position.amount:
            position.amount = Decimal(request.POST['edit_amount' + str(position.id)])
            position.save()                
    return HttpResponseRedirect(request.POST.get('next', '/portfolio/'))

我无法完成这项工作。帮助菜鸟?

【问题讨论】:

  • request.POST.get('id') 是否返回某些内容(不是None)?我没有看到您的表单在某处设置了id 字段?
  • 您应该将其发布为答案,因为它是正确的。除非他有一些他决定不显示的 JS,否则 id 永远不会被发布,所以它当然会返回 None
  • 我还想添加此代码还有许多其他问题。使用
  • 使用 没有任何问题。它比 更容易使用。它看起来确实像操作隐藏按钮并做一些javascript技巧以提交表单。这是个坏主意。
  • @nijansen

标签: python html django


【解决方案1】:

就像上面的评论者所说,表单没有发布任何名为“id”的字段。你想要的是“edit_amount{{ id }}”。

这是一个如何从表单字段名称中提取 ID 的示例。它缺少exception catching 和您需要注意的其他一些“陷阱”。但这是基本思想。

我确实建议您添加带有 ID 的 hidden form field,而不是这样做。您还应该check the permissions 的用户,并确保他们能够修改该特定记录。

@login_required
def edit(request):
   # Skipping the first couple lines.
   id = None
   for key in request.POST.keys():
       if 'edit_amount' in key:
           id = int(key[11:])

   position = InvestorPosition.objects.get(id=id)

   position.amount = Decimal(request.POST.get('edit_amount%s' % id))
   position.save()

   return HttpResponseRedirect(request.POST.get('next', '/portfolio/'))

【讨论】:

  • 这对您很有帮助,谢谢。添加隐藏输入后,错误不再出现。
猜你喜欢
  • 2017-06-10
  • 1970-01-01
  • 1970-01-01
  • 2016-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-20
  • 2021-07-05
相关资源
最近更新 更多