From 693680ba583ed52272b0aa84cecef52637675c71 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=B4mulo=20Penido?= Date: Mon, 8 Sep 2025 14:10:47 -0300 Subject: [PATCH] fix: unlink broken link (#37329) This fixes a bug that occurs when unlinking a block from a downstream block that has a broken link --- .../rest_api/v2/views/downstreams.py | 24 +++++++++---------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/cms/djangoapps/contentstore/rest_api/v2/views/downstreams.py b/cms/djangoapps/contentstore/rest_api/v2/views/downstreams.py index e95dac4890..d417707029 100644 --- a/cms/djangoapps/contentstore/rest_api/v2/views/downstreams.py +++ b/cms/djangoapps/contentstore/rest_api/v2/views/downstreams.py @@ -456,25 +456,23 @@ class DownstreamView(DeveloperErrorViewMixin, APIView): """ downstream = _load_accessible_block(request.user, usage_key_string, require_write_access=True) affected_blocks: list[XBlock] = [] + # Get the upstream ref before severing the link, so we can delete + # the corresponding ComponentLink or ContainerLink below. + upstream_ref = downstream.upstream try: - # Try to get the upstream key before severing the link, so we can delete - # the corresponding ComponentLink or ContainerLink below. - try: - upstream_key = UpstreamLink.get_for_block(downstream).upstream_key - except NoUpstream: - # Even if we don't have an UpstreamLink, we still need to check - # if the block has the upstream key set, so we don't want to - # raise an exception here. - upstream_key = None affected_blocks = sever_upstream_link(downstream) # Remove the ComponentLink or ContainerLink, if it exists. - if upstream_key: - if isinstance(upstream_key, LibraryUsageLocatorV2): + if upstream_ref: + try: ComponentLink.get_by_downstream_usage_key(downstream.usage_key).delete() - elif isinstance(upstream_key, LibraryContainerLocator): - ContainerLink.get_by_downstream_usage_key(downstream.usage_key).delete() + except ComponentLink.DoesNotExist: + try: + ContainerLink.get_by_downstream_usage_key(downstream.usage_key).delete() + except ContainerLink.DoesNotExist: + # If neither link exists, that's fine--we just wanted to clean up if possible. + pass except NoUpstream: logger.exception( "Tried to DELETE upstream link of '%s', but it wasn't linked to anything in the first place. "