2012-03-28 18 views
1

试图允许用户编辑小数值“数量”。当用户点击“编辑”时,会出现一个小数位字段。当用户完成改变的价值和 “完成” 点击...使用输入编辑模型。 ValueError

它抛出这个错误:

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/')) 

我无法完成这项工作。帮助noob出来?

+4

是否request.POST.get('id')'返回一些东西(那不是'None')?我没有看到你的表单设置了'id'字段? – nijansen 2012-03-28 20:01:38

+0

你应该发布这个答案,因为它是正确的。除非他有一些JS,否则他决定不显示,那么这个ID永远不会被发布,所以当然它会返回无。 – John 2012-03-28 20:07:49

+0

我还想添加此代码有许多其他问题。使用

回答

2

就像上面的评论者所说,表单不会发布任何名为“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/')) 
+0

这非常有帮助谢谢。添加隐藏的输入后,错误不再出现。 – Modelesq 2012-03-28 21:00:54