def run_test(self, request, object_id=None):
"""
Takes an HttpRequest with data from a ConfigToolForm and the
object id for a Model instance. Creates a temporary version
of the Model instance using the form data and returns a
JsonResponse with the result of the configuration test.
"""
try:
with transaction.atomic():
forms_are_valid = True
form = self._create_form_instance(request, object_id)
if form.is_valid():
instance = form.save()
# pass the parent model instance to the formsets to create
# related instances
formsets = self._create_formset_instances(request, instance)
if self._formsets_are_valid(formsets):
for formset in formsets:
formset.save()
# all models are now saved, so get the test result
result = self._get_result(form, instance)
else:
forms_are_valid = False
else:
formsets = []
forms_are_valid = False
if not forms_are_valid:
result = self._format_errors(form, formsets)
# rollback the database when exiting the atomic block
transaction.set_rollback(True)
except IntegrityError as error:
LOGGER.error('An error occurred while creating a test instance: %s', request)
result = 'Could not create an object for testing: %s' % error
except ValidationError as error:
LOGGER.error('An error occurred while initializing a config test: %s', request)
result = 'A validation error occurred: %s' % error
return JsonResponse({'result': result})
评论列表
文章目录