samedi 6 janvier 2018

formset invalid django test

Can't understand what I'm doing wrong here and would appreciate some insight. been trying to figure it for a couple hours now.

Test is simple. Just want to validate a formset.

The form is invalid and shows errors for two of the attributes as per below.

1) 'account' is a foreignkey to another model. i have tried changing the values to match the PK for each account, i've tried changing the key to 'account_id', thinking i might have the wrong attribute. can't seem to make it work.

2) 'file' is a FileField, to which I'm passing the string of the file path, which isn't being recognized at all. I'm not sure if there's some different structure for file uploads that I am missing completely.

Here is the output from formset.errors:

[
 {
  'account': ['Select a valid choice. That choice is not one of the available 
              choices.'], 
  'file': ['This field is required.']
 },
 {
  'account': ['Select a valid choice. That choice is not one of the available 
              choices.'], 
  'file': ['This field is required.']
  }
]

i found a handy helper function to put together the formset data here. The formset data looks like this:

{
 'form-INITIAL_FORMS': 0, 
 'form-TOTAL_FORMS': 2, 
 'form-1-account': 'RRSP'
 'form-1-file': 'reports/investments/RRSP/RRSP_2017-12-27_m8q4m0v.xls', 
 'form-1-date': datetime.datetime(2017, 12, 27, 0, 0), 
 'form-1-datetime_upload': datetime.datetime(2018, 1, 5, 2, 40, 25, 270753), 
 'form-0-date': datetime.datetime(2017, 12, 27, 0, 0), 
 'form-0-account': 'Investment', 
 'form-0-datetime_upload': datetime.datetime(2018, 1, 5, 2, 40, 25, 270753), 
 'form-0-file': 'reports/investments/Investment/Investment_2017-12- \
                 27_8GMEvGb.xls',
 }

Here's the test:

def test_invmt_report_formset(self):
    report_date = dt(2017,12,27,0,0)
    upload_date = dt(2018,1,5,2,40,25,270753)

    formset_data = self.set_formset_data(report_date, upload_date)
    InvmtReportsFormSet = modelformset_factory(InvmtReports,
                                                InvmtReportsForm,
                                                extra=4,
                                                )
    formset = instantiate_formset(InvmtReportsFormSet, data=formset_data)

    formset = self.get_formset(report_date, upload_date)

    formset.is_valid()
    print (formset.errors)

    self.assertTrue(formset.is_valid())

And here is the model with some of the functions/methods omitted.

class InvmtReports(Model):
    account = ForeignKey(Accounts, on_delete=CASCADE)
    date = DateField('Report Date')
    file = FileField('Report File', upload_to=get_file_path, validators=[validate_file_extension])
    datetime_upload = DateTimeField('Upload Date & Time', default=dt.datetime.now())

Aucun commentaire:

Enregistrer un commentaire