def save(self, request, token=None, *args, **kwargs): """Create interactions from a CSV file that was loaded in the select_file view.""" form = InteractionCSVForm.from_token(token) if not form: self.model_admin.message_user(request, INVALID_TOKEN_MESSAGE_DURING_SAVE, ERROR) return _redirect_response('changelist') if not form.is_valid(): # This should not happen, so we simply raise an error to alert us if it does raise DataHubException('Unexpected form re-validation failure') matching_counts, unmatched_row_collector = form.save(request.user) save_result_counts_by_status(token, matching_counts) unmatched_rows_csv_contents = unmatched_row_collector.to_raw_csv() if unmatched_rows_csv_contents: save_unmatched_rows_csv_contents(token, unmatched_rows_csv_contents) # Redirect to another page to display a confirmation message on success (following the # standard Django pattern to limit the possibility of a form resubmission on page # refresh). # For consistency, the required state is kept in the cache. return _redirect_response('import-complete', token=token)
def test_from_token_with_invalid_token(self, cache_data): """ Test that from_token() returns None if there is incomplete data for the token in the cache. """ cache.set_many(cache_data) form = InteractionCSVForm.from_token('test-token') assert form is None
def test_from_token_with_valid_token(self): """Test that a form can be restored from the cache.""" token = 'test-token' contents_key = _cache_key_for_token(token, CacheKeyType.file_contents) name_key = _cache_key_for_token(token, CacheKeyType.file_name) file = make_csv_file_from_dicts( *make_matched_rows(1), filename='cache-test.csv', ) compressed_data = gzip.compress(file.read()) cache.set(contents_key, compressed_data) cache.set(name_key, file.name) form = InteractionCSVForm.from_token(token) assert form.is_valid() file.seek(0) assert file.read() == form.cleaned_data['csv_file'].read() assert file.name == form.cleaned_data['csv_file'].name