Django验证错误u“”值必须是十进制数。“ [英] Django validation error u"'' value must be a decimal number."

查看:398
本文介绍了Django验证错误u“”值必须是十进制数。“的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从表单获取数据,表单根据列表多次转载。每个项目的一种形式。该表单由复选框和文本框组成。如果选中该复选框,那么我还需要附带的文本域数据。

I am trying to get data from a form, the form is reproduced a number of times based on a list. One form for each item. The form consists of a checkbox and a textfield. If the checkbox is checked then I need the accompanying textfield data as well.

查看:

        for item in request.POST.getlist('item_list'):
            item_id = int(item)
            item = Item.objects.get(id=item_id)
            item_name = item.name
            print item_name


            list = List(name = item_name, created_on = now, edited_on = now)

            for price in request.POST.getlist('price'):
                print price
                list_item.price = price
                list_item.save()
            #item.delete()

它未显示在上面,但 now = timezone.now()

Its not shown above but now = timezone.now().

模板:

<form action="" method="post">

    {% csrf_token %}

    {% for item in item_list %}
        <input type="checkbox" name="item" value="{{item.id}}">{{item.name}} <input type="text" name="price"><br>
    {% endfor %}

    <input type="submit" value="Add Items">

</form>

这将返回一个validationerror [u值必须是十进制数。] 。我不知道为什么会说我输入的数字不是小数。感谢您的帮助。

This returns a validationerror [u"'' value must be a decimal number."]. I can't figure out why it would be saying the numbers I'm inputting are not decimals. Thanks for your help.

更新:

当我输入打印请求时的输出.POST.getlist('price') [u'2.55',u'4.32',u'23.421',u'3.00',u ']

推荐答案

有空的价格

There are empty prices in the list, skip them. Also, cast strings to decimals:

from decimal import Decimal

...

for price in request.POST.getlist('price'):
    if not price:
        continue
    list_item.price = Decimal(price)
    list_item.save()

这篇关于Django验证错误u“”值必须是十进制数。“的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆