ValidationError无效的日期格式

时间:2017-02-07 22:30:47

标签: python django django-models

我正在尝试从csv文件中提取数据并将条目读入我的数据库。

回溯:

File "/home/paragoncdn/webapps/hdcportal/lib/python2.7/Django-1.8.2-py2.7.egg/django/core/handlers/base.py", line 132, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/paragoncdn/webapps/hdcportal/lib/python2.7/Django-1.8.2-py2.7.egg/django/contrib/auth/decorators.py", line 22, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/home/paragoncdn/webapps/hdcportal/myproject/contracts/views.py", line 445, in csv_import
errors_found = csvtools.process_csv(request, csv_file)
File "/home/paragoncdn/webapps/hdcportal/myproject/contracts/csvtools.py", line 143, in process_csv
line_sample.save()
File "/home/paragoncdn/webapps/hdcportal/lib/python2.7/Django-1.8.2-py2.7.egg/django/db/models/base.py", line 710, in save
force_update=force_update, update_fields=update_fields)
File "/home/paragoncdn/webapps/hdcportal/lib/python2.7/Django-1.8.2-py2.7.egg/django/db/models/base.py", line 738, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/home/paragoncdn/webapps/hdcportal/lib/python2.7/Django-1.8.2-py2.7.egg/django/db/models/base.py", line 822, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/home/paragoncdn/webapps/hdcportal/lib/python2.7/Django-1.8.2-py2.7.egg/django/db/models/base.py", line 861, in _do_insert
using=using, raw=raw)
File "/home/paragoncdn/webapps/hdcportal/lib/python2.7/Django-1.8.2-py2.7.egg/django/db/models/manager.py", line 127, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/paragoncdn/webapps/hdcportal/lib/python2.7/Django-1.8.2-py2.7.egg/django/db/models/query.py", line 920, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/home/paragoncdn/webapps/hdcportal/lib/python2.7/Django-1.8.2-py2.7.egg/django/db/models/sql/compiler.py", line 973, in execute_sql
for sql, params in self.as_sql():
File "/home/paragoncdn/webapps/hdcportal/lib/python2.7/Django-1.8.2-py2.7.egg/django/db/models/sql/compiler.py", line 931, in as_sql
for obj in self.query.objs
File "/home/paragoncdn/webapps/hdcportal/lib/python2.7/Django-1.8.2-py2.7.egg/django/db/models/fields/__init__.py", line 710, in get_db_prep_save
prepared=False)
File "/home/paragoncdn/webapps/hdcportal/lib/python2.7/Django-1.8.2-py2.7.egg/django/db/models/fields/__init__.py", line 1322, in get_db_prep_value
value = self.get_prep_value(value)
File "/home/paragoncdn/webapps/hdcportal/lib/python2.7/Django-1.8.2-py2.7.egg/django/db/models/fields/__init__.py", line 1317, in get_prep_value
return self.to_python(value)
File "/home/paragoncdn/webapps/hdcportal/lib/python2.7/Django-1.8.2-py2.7.egg/django/db/models/fields/__init__.py", line 1287, in to_python
params={'value': value},
ValidationError: [u"'2/7/2017' value has an invalid date format. It must be in YYYY-MM-DD format."]

迁移:

 migrations.CreateModel(
        name='Sample',
        fields=[
            ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
            ('sample_number', models.CharField(help_text=b'Depends on the group of samples this sample was sent with.', max_length=20, blank=True)),
            ('date_created', models.DateField(auto_now_add=True)),
            ('status', models.CharField(help_text=b'What stage the contract is in.', max_length=20, blank=True)),
            ('po', models.CharField(help_text=b'Purchase order.', max_length=200, blank=True)),
            ('date_received', models.DateField(null=True, blank=True)),
            ('flexural_strength_and_modulus_test', models.BooleanField(default=False, verbose_name=b'Flexural Strength & Modulus (ASTM D790)')),
            ('wall_thickness_test', models.BooleanField(default=False, verbose_name=b'Wall Thickness (ASTM D5813)')),
            ('tensile_strength_test', models.BooleanField(default=False, verbose_name=b'Tensile Strength (ASTM D638)')),
            ('APS_water_tightness_test', models.BooleanField(default=False, verbose_name=b'APS Water Tightness (APS)')),
            ('FTIR_test', models.BooleanField(default=False, verbose_name=b'FTIR Resin Analysis (ASTM E1252)')),
            ('other_test', models.CharField(help_text=b'If your required test is not listed, please enter it.', max_length=100, blank=True)),
            ('street', models.CharField(max_length=100)),
            ('diameter', models.DecimalField(help_text=b'Units: mm', max_digits=8, decimal_places=2)),
            ('thickness', models.DecimalField(help_text=b'Units: mm', max_digits=8, decimal_places=2)),
            ('installation_date', models.DateField(help_text=b'Please enter in the following format: MM/DD/YYYY')),
            ('mh1', models.CharField(max_length=15)),
            ('mh2', models.CharField(max_length=15)),
            ('shot', models.CharField(max_length=15)),
            ('sec', models.CharField(max_length=15)),
            ('mh_to_mh', models.CharField(max_length=15, blank=True)),
            ('shot_and_sec', models.CharField(max_length=15, blank=True)),
            ('other', models.CharField(max_length=30, blank=True)),
            ('batch', models.ForeignKey(blank=True, to='contracts.Batch', null=True)),
            ('contract', models.ForeignKey(blank=True, to='contracts.Contract', help_text=b'The contract that this sample belongs to.', null=True)),
        ],
        options={
            'db_table': 'sample',
        },
    )

老实说,我不太确定如何将格式更改为ValidationError中请求的格式。我目前正在阅读数据的方式是:

sample_fields = [
    'street', 'diameter', 'thickness', 'installation_date',  'mh_to_mh', 'shot_and_sec', 'other',
    'flexural_strength_and_modulus_test', 'wall_thickness_test', 'tensile_strength_test',
    'APS_water_tightness_test', 'FTIR_test', 'other_test',
]
...
for num, line in lines:
        try:
            # creates a dictionary of all the field names for sample fields
            # and the values in the csv file
            sample_dict = {k: line[k] for k in sample_fields}
            # creates a dictionary of all the field names for parameter_fields
            # and the values in the csv file
            parameter_dict = {k: line[k] for k in parameter_fields}

            # this is working because when the except is commented out the 
            # csv will create the contracts, but the samples are not added
            # if the contract in the csv is not already in the contracts list then
            if line['contract_no'] not in contracts:
                #create the contract with the company, contract_no and rec_required
                contract = Contract(client=company,
                                    contract_no=line['contract_no'],
                                    reconciliation_required=True if line['reconciliation_required'] == '1' else False)
                contract.save()
                contracts[line['contract_no']] = contract
                #errors_found.append('Here')

            # using the Sample function from models.py pass it the 
            # dictionary for the line and create the line_sample
            # sample_fields
            #'street', 'diameter', 'thickness', 'installation_date', 'mh_to_mh', 'shot_and_sec', 'other',
            #'flexural_strength_and_modulus_test', 'wall_thickness_test', 'tensile_strength_test',
            #'APS_water_tightness_test', 'FTIR_test', 'other_test',

            line_sample = Sample(**sample_dict)
            #line_sample = Sample.objects.create(**sample_dict)
            line_sample.contract = contracts[line['contract_no']]
            line_sample.status = 'Pending'
            #errors_found.append('Or Here')

            # if the contract requires reconciliation then
            if contracts[line['contract_no']].reconciliation_required:
                # pass SampleDesignParameters the parameter dictionary and create line_parameters
                line_parameters = SampleDesignParameters(**parameter_dict)
                line_parameters.contract = contracts[line['contract_no']]
                line_parameters.name = 'Auto-Created'
                line_parameters.save()
                line_sample.parameters = line_parameters
                #errors_found.append('Maybe Here')

            # error is here, line sample is not saving correctly
            line_sample.save()

        except:
            errors_found.append('There is an issue with sample #' + str(num) + '. Ensure fields have valid inputs.')
            #for contract in contracts.values():
            #    contract.sample_set.all().delete()
            #    contract.designparameters_set.all().delete()
            #    contract.delete()

            #break

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

Django不接受CSV中的日期格式。它希望以“YYYY-MM-DD”格式读取日期,并且您的CSV以“M / D / YYYY”格式显示它们。

您有几个选项可以解决此问题:

  1. 更改CSV的日期格式,以符合Django的要求 期待
  2. 更改设置中的预期日期格式。对于     信息:https://docs.djangoproject.com/en/1.8/ref/settings/#date-input-formats