2017-02-07 5 views
0

Я пытаюсь извлечь данные из файла csv и прочитать записи в моей базе данных.ValidationError неверный формат даты

Traceback:

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', 
     }, 
    ) 

Im честно не слишком уверен, как идти об изменении формата в формат запрошенный в 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 

Любая помощь будет очень признательна!

+0

Traceback говорит ваша ошибка в 'строке 1287, в to_python', вы можете показать нам, что часть кода? – Alex

ответ

0

Django не принимает формат даты с вашего CSV. Ожидается, что даты будут даны в формате «ГГГГ-ММ-ДД», а ваш CSV будет иметь их в формате «M/D/YYYY».

У вас есть несколько вариантов, чтобы исправить это:

  1. изменить формат даты вашего CSV, чтобы выполнить то, что Django является ожидает
  2. Измените ожидаемый формат даты в настройках. Для информации: https://docs.djangoproject.com/en/1.8/ref/settings/#date-input-formats
Смежные вопросы