验证错误:[u"''值必须是十进制数。"] django

时间:2015-07-14 08:13:29

标签: django django-models django-forms

我有一个模型如下

class ExampleModel(models.Model)"
    price_one = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True)
    price_two = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True)

我没有ModelForm或只是上述型号的Form,由于某些原因,它显示为html术语如下

<form class="check_foreign_keys" action="." method="post">
.......
.......
<div class="text-field">
    <label>Price One(US$)</label>
    <div class="input-area">
        <input type="text" name="price_one" id="price_one" value="{{ example_model_obj.price_one }}" />
    </div>
</div>
<div class="text-field">
    <label>Price Two(US$)</label>
    <div class="input-area">
        <input type="text" name="price_two" id="price_two" value="{{ example_model_obj.price_two }}" />
    </div>
</div>
 <input type="submit" value="Save Changes" class="fancy-blue-button" />
</form>

Views.py(实施例)

if request.method == 'POST':
    obj, created = ExampleModel.objects.get_or_create(price_one=request.POST['price_one'],price_one=request.POST['price_two']......)
    obj.save()

错误:

  File "/Users/username/.virtualenvs/project/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 850, in to_python
    raise exceptions.ValidationError(msg)
ValidationError: [u"'' value must be a decimal number."]

这里究竟是什么问题,如果没有为price_oneprice_two提供任何价值,那么它的价值就是&#39;&#39;这是我想要的,但作为字段DecimalField它不接受字符串/空值,即使我已在模型中为字段放置null=Trueblank=True

此外,我在google上看到,如果我们使用django.forms.DecimalField,上述错误可能会消失,但我在这里没有使用django表单,只是直接显示html元素。

所以我想要的是取空(&#39;&#39;)值并保存到数据库,而不会出现上述错误ValidationError: [u"'' value must be a decimal number."]

有谁能让我知道如何解决上述错误?

1 个答案:

答案 0 :(得分:0)

我遇到了类似的问题,并相信找到了解决方案。我注意到错误报告有两个部分(见下文)。重要的一行是第6行:

应用store.0005_product_discount_price ...回溯(最近一次调用最后一次)

&#13;
&#13;
C:\Users\mnede\PycharmProjects\SeshWebsite\SeshStore\static
Operations to perform:
  Apply all migrations: admin, auth, blog, contenttypes, home, sessions, store, taggit, wagtailadmin, wagtailcore, wagtaildocs, wagtailembeds, wagtailforms,
 wagtailimages, wagtailredirects, wagtailsearch, wagtailusers
Running migrations:
  Applying store.0005_product_discount_price...Traceback (most recent call last):
  File "C:\Python\Python36\lib\site-packages\django\db\models\fields\__init__.py", line 1554, in to_python
    return decimal.Decimal(value)
decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 12, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line
    utility.execute()
  File "C:\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 359, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Python\Python36\lib\site-packages\django\core\management\base.py", line 294, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Python\Python36\lib\site-packages\django\core\management\base.py", line 345, in execute
    output = self.handle(*args, **options)
  File "C:\Python\Python36\lib\site-packages\django\core\management\commands\migrate.py", line 204, in handle
    fake_initial=fake_initial,
  File "C:\Python\Python36\lib\site-packages\django\db\migrations\executor.py", line 115, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "C:\Python\Python36\lib\site-packages\django\db\migrations\executor.py", line 145, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "C:\Python\Python36\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration
    state = migration.apply(state, schema_editor)
  File "C:\Python\Python36\lib\site-packages\django\db\migrations\migration.py", line 129, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "C:\Python\Python36\lib\site-packages\django\db\migrations\operations\fields.py", line 84, in database_forwards
    field,
  File "C:\Python\Python36\lib\site-packages\django\db\backends\mysql\schema.py", line 43, in add_field
    super(DatabaseSchemaEditor, self).add_field(model, field)
  File "C:\Python\Python36\lib\site-packages\django\db\backends\base\schema.py", line 395, in add_field
    definition, params = self.column_sql(model, field, include_default=True)
  File "C:\Python\Python36\lib\site-packages\django\db\backends\base\schema.py", line 147, in column_sql
    default_value = self.effective_default(field)
  File "C:\Python\Python36\lib\site-packages\django\db\backends\base\schema.py", line 221, in effective_default
    default = field.get_db_prep_save(default, self.connection)
  File "C:\Python\Python36\lib\site-packages\django\db\models\fields\__init__.py", line 1583, in get_db_prep_save
    return connection.ops.adapt_decimalfield_value(self.to_python(value), self.max_digits, self.decimal_places)
  File "C:\Python\Python36\lib\site-packages\django\db\models\fields\__init__.py", line 1559, in to_python
    params={'value': value},
django.core.exceptions.ValidationError: ["'' value must be a decimal number."]
&#13;
&#13;
&#13;

原来我的model.py字段中没有发生错误,但实际上发生在我的迁移文件中。

根据错误报告,我在迁移文件夹中选择了 0005_product_discount_price.py ,并注意到尝试执行的迁移django仍然包含错误的默认值。

&#13;
&#13;
class Migration(migrations.Migration):

    dependencies = [
        ('store', '0004_productpagegalleryimage'),
    ]

    operations = [
        migrations.AddField(
            model_name='product',
            name='discount_price',
            field=models.DecimalField(decimal_places=2, default='', max_digits=10),
        ),
    ]
&#13;
&#13;
&#13;

我从十进制导入十进制

导入时解决了该问题

并更改了我的代码如下:

&#13;
&#13;
from __future__ import unicode_literals

from django.db import migrations, models
from decimal import Decimal


class Migration(migrations.Migration):

    dependencies = [
        ('store', '0004_productpagegalleryimage'),
    ]

    operations = [
        migrations.AddField(
            model_name='product',
            name='discount_price',
            field=models.DecimalField(decimal_places=2, default=Decimal(0), max_digits=10),
        ),
    ]
&#13;
&#13;
&#13;

Django继续尝试执行false语句,导致两个错误报告类似于你自己遇到的错误报告。

希望这有帮助。

ž