简体   繁体   English

Django模型中的ValidationError

[英]ValidationError in Django Model

I defined the Test model as: 我将Test模型定义为:

class Test(models.Model):

    name = models.BinaryField(blank=False)
    time = models.TimeField()

    # one test case has many tests
    testcase = models.ForeignKey(TestCase)

    def __str__(self):
        return self.name

when I try to parse a xml file to create the model object I have the following method: 当我尝试解析xml文件来创建模型对象时,我有以下方法:

def add_test(testcase, obj):
    kwargs = {
        'name': "",
        'time': None,
    }
    status = 1
    # create the test object
    for k, v in obj.iteritems():
        if k == '@name':
            kwargs['name'] = v if v is not None else ""
        elif k == '@time':
            kwargs['time'] = v
    print kwargs
    test = Test(testcase=testcase, **kwargs)
    test.save()

There, testcase is the oject of the TestCase model. 在那里, testcaseTestCase模型的对象。 The kwargs have the correct input: kwargs有正确的输入:

{'name': u'runTest', 'time': u'36.332'}

However, when I invoke the above function I get: 但是,当我调用上面的函数时,我得到:

Traceback (most recent call last):
  File "dbsync.py", line 131, in <module>
    add_testsuite("scale")
  File "dbsync.py", line 55, in add_testsuite
    add_testcases(testsuite, testcases)
  File "dbsync.py", line 87, in add_testcases
    status = add_test(testcase_obj, testcase)
  File "dbsync.py", line 103, in add_test
    test.save()
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 710, in save
    force_update=force_update, update_fields=update_fields)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 738, in save_base
    updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 822, in _save_table
    result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 861, in _do_insert
    using=using, raw=raw)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py", line 127, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 920, in _insert
    return query.get_compiler(using=using).execute_sql(return_id)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 970, in execute_sql
    for sql, params in self.as_sql():
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 928, in as_sql
    for obj in self.query.objs
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 710, in get_db_prep_save
    prepared=False)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 2293, in get_db_prep_value
    value = self.get_prep_value(value)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 2288, in get_prep_value
    return self.to_python(value)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 2275, in to_python
    params={'value': value},
django.core.exceptions.ValidationError

I don't quite get what's going on there ... any clues? 我不太了解那里发生的事情......任何线索?

To make this work you have to convert your string into a datetime.time. 要完成这项工作,您必须将字符串转换为datetime.time。

kwargs['time'] = datetime.datetime.strptime(v, 'YOUR_TIME_FORMAT').time()

Replace YOUR_TIME_FORMAT with the input time format you have. 将YOUR_TIME_FORMAT替换为您拥有的输入时间格式。

It's not complaining about the way you pass in your variables, it's raising a ValidationError and I have a funny feeling that it's missing the last line of the traceback, which would tell us what is wrong with your values. 它没有抱怨你传递变量的方式,它引发了ValidationError ,我有一种有趣的感觉,它错过了追溯的最后一行,这会告诉我们你的价值有什么问题。

I didn't test the BinaryField , but the TimeField is complaining about your value. 我没有测试BinaryField ,但TimeField抱怨你的价值。 I haven't tested the BinaryField, but just looking at the TimeField , shows the following: 我没有测试过BinaryField,只是看一下TimeField ,显示如下:

  File "<console>", line 1, in <module>
  File "/home/paco/Projects/sandeepbox/stackoverflow/bla/bla/field_validation.py", line 16, in <module>
    print a.is_valid()
  File "/home/paco/.virtualenvs/berou/local/lib/python2.7/site-packages/django/forms/forms.py", line 184, in is_valid
    return self.is_bound and not self.errors
  File "/home/paco/.virtualenvs/berou/local/lib/python2.7/site-packages/django/forms/forms.py", line 176, in errors
    self.full_clean()
  File "/home/paco/.virtualenvs/berou/local/lib/python2.7/site-packages/django/forms/forms.py", line 392, in full_clean
    self._clean_fields()
  File "/home/paco/.virtualenvs/berou/local/lib/python2.7/site-packages/django/forms/forms.py", line 407, in _clean_fields
    value = field.clean(value)
  File "/home/paco/.virtualenvs/berou/local/lib/python2.7/site-packages/django/forms/fields.py", line 162, in clean
    value = self.to_python(value)
  File "/home/paco/.virtualenvs/berou/local/lib/python2.7/site-packages/django/forms/fields.py", line 474, in to_python
    return super(TimeField, self).to_python(value)
  File "/home/paco/.virtualenvs/berou/local/lib/python2.7/site-packages/django/forms/fields.py", line 423, in to_python
    for format in self.input_formats:
  File "/home/paco/.virtualenvs/berou/local/lib/python2.7/site-packages/django/utils/functional.py", line 136, in __wrapper__
    res = func(*self.__args, **self.__kw)
  File "/home/paco/.virtualenvs/berou/local/lib/python2.7/site-packages/django/utils/formats.py", line 110, in get_format
    for module in get_format_modules(lang):
  File "/home/paco/.virtualenvs/berou/local/lib/python2.7/site-packages/django/utils/formats.py", line 82, in get_format_modules
    modules = _format_modules_cache.setdefault(lang, list(iter_format_modules(lang, settings.FORMAT_MODULE_PATH)))
  File "/home/paco/.virtualenvs/berou/local/lib/python2.7/site-packages/django/utils/formats.py", line 51, in iter_format_modules
    if not check_for_language(lang):
  File "/home/paco/.virtualenvs/berou/local/lib/python2.7/site-packages/django/utils/translation/__init__.py", line 181, in check_for_language
    return _trans.check_for_language(lang_code)
  File "/home/paco/.virtualenvs/berou/local/lib/python2.7/site-packages/django/utils/lru_cache.py", line 125, in wrapper
    result = user_function(*args, **kwds)
  File "/home/paco/.virtualenvs/berou/local/lib/python2.7/site-packages/django/utils/translation/trans_real.py", line 409, in check_for_language
    if not language_code_re.search(lang_code):
TypeError: expected string or buffer

with the following code (no need for models to show the validation): 使用以下代码(不需要模型来显示验证):

from django import forms


class Test(forms.Form):
    time = forms.TimeField()

    def __str__(self):
        return self.name


kwargs = {'time': u'36.332'}
a = Test(kwargs)
print a.is_valid()

You need to pass in your data this way: 您需要以这种方式传递数据:

import datetime

from django import forms


class Test(forms.Form):
    time = forms.TimeField()

    def __str__(self):
        return self.name


kwargs = {'time': datetime.datetime.now().time()}
a = Test(kwargs)
print a.is_valid()

The code, this time, actually prints True 这次代码实际上打印为True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM