Skip to content

Commit

Permalink
Provide the user with an error if import fails
Browse files Browse the repository at this point in the history
  • Loading branch information
willbarton committed Sep 20, 2024
1 parent 072d66c commit d17c997
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 4 deletions.
47 changes: 47 additions & 0 deletions cfgov/archival/tests/test_views.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import json
from io import StringIO

from django.test import TestCase
Expand Down Expand Up @@ -91,3 +92,49 @@ def test_import_view_get(self):
)
self.assertEqual(response.status_code, 200)
self.assertIn("form", response.context)

def test_import_view_post_app_does_not_exist(self):
page_json = json.dumps(
{
"app_label": "app_does_not_exist",
"model": "blogpage",
"last_migration": "",
"data": {},
}
)
page_io = StringIO(page_json)

# Log in and post it
self.login()
response = self.client.post(
reverse("import_page", kwargs={"page_id": self.root_page.id}),
{"page_file": page_io},
)
self.assertTrue(len(response.context["form"].errors["page_file"]) > 0)
self.assertIn(
"There was an error importing this file as a page.",
response.context["form"].errors["page_file"][0],
)

def test_import_view_post_model_does_not_exist(self):
page_json = json.dumps(
{
"app_label": "v1",
"model": "PageModelDoesNotExist",
"last_migration": "",
"data": {},
}
)
page_io = StringIO(page_json)

# Log in and post it
self.login()
response = self.client.post(
reverse("import_page", kwargs={"page_id": self.root_page.id}),
{"page_file": page_io},
)
self.assertTrue(len(response.context["form"].errors["page_file"]) > 0)
self.assertIn(
"There was an error importing this file as a page.",
response.context["form"].errors["page_file"][0],
)
17 changes: 13 additions & 4 deletions cfgov/archival/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,19 @@ def import_view(request, page_id):

if input_form.is_valid():
json_file = request.FILES["page_file"]
new_page = import_page(
parent_page, json_file.read().decode("utf8")
)
return redirect("wagtailadmin_pages:edit", new_page.id)
try:
new_page = import_page(
parent_page, json_file.read().decode("utf8")
)
except Exception:
input_form.add_error(
"page_file",
"There was an error importing this file as a page. "
"Please ensure the app and model it references exist, "
"and that its schema is up to date.",
)
else:
return redirect("wagtailadmin_pages:edit", new_page.id)
else:
input_form = ImportForm()

Expand Down

0 comments on commit d17c997

Please sign in to comment.