fix: unlink broken link (#37329)

This fixes a bug that occurs when unlinking a block from a downstream block that has a broken link
This commit is contained in:
Rômulo Penido
2025-09-08 14:10:47 -03:00
committed by GitHub
parent ed45fbba37
commit 693680ba58

View File

@@ -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. "