diff --git a/src/backend/InvenTree/report/templatetags/report.py b/src/backend/InvenTree/report/templatetags/report.py index aad9db84b5..f5d0856dd1 100644 --- a/src/backend/InvenTree/report/templatetags/report.py +++ b/src/backend/InvenTree/report/templatetags/report.py @@ -451,8 +451,13 @@ def uploaded_image( @register.simple_tag() -def encode_svg_image(filename: str) -> str: - """Return a base64-encoded svg image data string.""" +def encode_svg_image(filename: str, raise_error: bool = False) -> str: + """Return a base64-encoded svg image data string. + + Arguments: + filename: The filename of the svg image relative to the media root directory + raise_error: If True, raise an error if the file cannot be found (default = False) + """ if type(filename) is SafeString: # Prepend an empty string to enforce 'stringiness' filename = '' + filename @@ -465,7 +470,12 @@ def encode_svg_image(filename: str) -> str: # Read out the file contents # Note: This will check if the file exists, and raise an error if it does not - data = get_media_file_contents(filename) + data = get_media_file_contents(filename, raise_error=raise_error) + + # If the file is empty, return an empty string + # Note that if raise_error is True, the above function will raise a FileNotFoundError if the file does not exist + if not data: + return '' # Return the base64-encoded data return 'data:image/svg+xml;charset=utf-8;base64,' + base64.b64encode(data).decode( diff --git a/src/backend/InvenTree/report/test_tags.py b/src/backend/InvenTree/report/test_tags.py index 047ce6a686..52ed61adff 100644 --- a/src/backend/InvenTree/report/test_tags.py +++ b/src/backend/InvenTree/report/test_tags.py @@ -523,6 +523,17 @@ class ReportTagTest(PartImageTestMixin, InvenTreeTestCase): svg, ) + # Test with a missing SVG file - default behavior is to return an empty string + missing_path = 'missing_svg_image_123abc.svg' + self.assertEqual(report_tags.encode_svg_image(missing_path), '') + self.assertEqual( + report_tags.encode_svg_image(missing_path, raise_error=False), '' + ) + + # Test with a missing SVG file, with raise_error=True + with self.assertRaises(FileNotFoundError): + report_tags.encode_svg_image(missing_path, raise_error=True) + def test_part_parameter(self): """Test the part_parameter template tag.""" # Test with a valid part