# Buggy code
def custom_links(context, obj):
    """
    Render all applicable links for the given object.
    """
    content_type = ContentType.objects.get_for_model(obj)
    custom_links = CustomLink.objects.filter(content_type=content_type)
    if not custom_links:
        return ""

    # Pass select context data when rendering the CustomLink
    link_context = {
        "obj": obj,
        "debug": context["debug"],  # django.template.context_processors.debug
        "request": context["request"],  # django.template.context_processors.request
        "user": context["user"],  # django.contrib.auth.context_processors.auth
        "perms": context["perms"],  # django.contrib.auth.context_processors.auth
    }
    template_code = ""
    group_names = OrderedDict()

    for cl in custom_links:
        # Organize custom links by group
        if cl.group_name and cl.group_name in group_names:
            group_names[cl.group_name].append(cl)
        elif cl.group_name:
            group_names[cl.group_name] = [cl]

        # Add non-grouped links
        else:
            try:
                text_rendered = render_jinja2(cl.text, link_context)
                if text_rendered:
                    link_rendered = render_jinja2(cl.url, link_context)
                    link_target = ' target="_blank"' if cl.new_window else ""
                    template_code += LINK_BUTTON.format(
                        link_rendered, link_target, cl.button_class, text_rendered
                    )
            except Exception as e:
                template_code += (
                    '<a class="btn btn-sm btn-default" disabled="disabled" title="{}">'
                    '<i class="fa fa-warning"></i> {}</a>\n'.format(e, cl.name)
                )

    # Add grouped links to template
    for group, links in group_names.items():
        links_rendered = []

        for cl in links:
            try:
                text_rendered = render_jinja2(cl.text, link_context)
                if text_rendered:
                    link_target = ' target="_blank"' if cl.new_window else ""
                    link_rendered = render_jinja2(cl.url, link_context)
                    links_rendered.append(
                        GROUP_LINK.format(link_rendered, link_target, text_rendered)
                    )
            except Exception as e:
                links_rendered.append(
                    '<li><a disabled="disabled" title="{}"><span class="text-muted">'
                    '<i class="fa fa-warning"></i> {}</span></a></li>'.format(
                        e, cl.name
                    )
                )

        if links_rendered:
            template_code += GROUP_BUTTON.format(
                links[0].button_class, group, "".join(links_rendered)
            )

    return mark_safe(template_code)


# Traceback (KeyError)
Traceback (most recent call last):
File "/opt/netbox-2.9.6/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/opt/netbox-2.9.6/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/opt/netbox-2.9.6/venv/lib/python3.7/site-packages/django/views/generic/base.py", line 73, in view
return self.dispatch(request, *args, **kwargs)
File "/opt/netbox/netbox/utilities/views.py", line 123, in dispatch
return super().dispatch(request, *args, **kwargs)
File "/opt/netbox-2.9.6/venv/lib/python3.7/site-packages/django/views/generic/base.py", line 101, in dispatch
return handler(request, *args, **kwargs)
File "/opt/netbox/netbox/dcim/views.py", line 1094, in get
'show_interface_graphs': Graph.objects.filter(type__model='interface').exists(),
File "/opt/netbox-2.9.6/venv/lib/python3.7/site-packages/django/shortcuts.py", line 19, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "/opt/netbox-2.9.6/venv/lib/python3.7/site-packages/django/template/loader.py", line 62, in render_to_string
return template.render(context, request)
File "/opt/netbox-2.9.6/venv/lib/python3.7/site-packages/django/template/backends/django.py", line 61, in render
return self.template.render(context)
File "/opt/netbox-2.9.6/venv/lib/python3.7/site-packages/django/template/base.py", line 170, in render
return self._render(context)
File "/opt/netbox-2.9.6/venv/lib/python3.7/site-packages/django/test/utils.py", line 96, in instrumented_test_render
return self.nodelist.render(context)
File "/opt/netbox-2.9.6/venv/lib/python3.7/site-packages/django/template/base.py", line 938, in render
bit = node.render_annotated(context)
File "/opt/netbox-2.9.6/venv/lib/python3.7/site-packages/django/template/base.py", line 905, in render_annotated
return self.render(context)
File "/opt/netbox-2.9.6/venv/lib/python3.7/site-packages/django/template/loader_tags.py", line 150, in render
return compiled_parent._render(context)
File "/opt/netbox-2.9.6/venv/lib/python3.7/site-packages/django/test/utils.py", line 96, in instrumented_test_render
return self.nodelist.render(context)
File "/opt/netbox-2.9.6/venv/lib/python3.7/site-packages/django/template/base.py", line 938, in render
bit = node.render_annotated(context)
File "/opt/netbox-2.9.6/venv/lib/python3.7/site-packages/django/template/base.py", line 905, in render_annotated
return self.render(context)
File "/opt/netbox-2.9.6/venv/lib/python3.7/site-packages/django/template/loader_tags.py", line 62, in render
result = block.nodelist.render(context)
File "/opt/netbox-2.9.6/venv/lib/python3.7/site-packages/django/template/base.py", line 938, in render
bit = node.render_annotated(context)
File "/opt/netbox-2.9.6/venv/lib/python3.7/site-packages/django/template/base.py", line 905, in render_annotated
return self.render(context)
File "/opt/netbox-2.9.6/venv/lib/python3.7/site-packages/django/template/library.py", line 192, in render
output = self.func(*resolved_args, **resolved_kwargs)
File "/opt/netbox/netbox/extras/templatetags/custom_links.py", line 36, in custom_links
'debug': context['debug'],  # django.template.context_processors.debug
File "/opt/netbox-2.9.6/venv/lib/python3.7/site-packages/django/template/context.py", line 83, in __getitem__
raise KeyError(key)
Exception Type: KeyError at /dcim/devices/28/
Exception Value: 'debug'

# Fixed code
def custom_links(context, obj):
    """
    Render all applicable links for the given object.
    """
    content_type = ContentType.objects.get_for_model(obj)
    custom_links = CustomLink.objects.filter(content_type=content_type)
    if not custom_links:
        return ""

    # Pass select context data when rendering the CustomLink
    link_context = {
        "obj": obj,
        "debug": context.get(
            "debug", False
        ),  # django.template.context_processors.debug
        "request": context["request"],  # django.template.context_processors.request
        "user": context["user"],  # django.contrib.auth.context_processors.auth
        "perms": context["perms"],  # django.contrib.auth.context_processors.auth
    }
    template_code = ""
    group_names = OrderedDict()

    for cl in custom_links:
        # Organize custom links by group
        if cl.group_name and cl.group_name in group_names:
            group_names[cl.group_name].append(cl)
        elif cl.group_name:
            group_names[cl.group_name] = [cl]

        # Add non-grouped links
        else:
            try:
                text_rendered = render_jinja2(cl.text, link_context)
                if text_rendered:
                    link_rendered = render_jinja2(cl.url, link_context)
                    link_target = ' target="_blank"' if cl.new_window else ""
                    template_code += LINK_BUTTON.format(
                        link_rendered, link_target, cl.button_class, text_rendered
                    )
            except Exception as e:
                template_code += (
                    '<a class="btn btn-sm btn-default" disabled="disabled" title="{}">'
                    '<i class="fa fa-warning"></i> {}</a>\n'.format(e, cl.name)
                )

    # Add grouped links to template
    for group, links in group_names.items():
        links_rendered = []

        for cl in links:
            try:
                text_rendered = render_jinja2(cl.text, link_context)
                if text_rendered:
                    link_target = ' target="_blank"' if cl.new_window else ""
                    link_rendered = render_jinja2(cl.url, link_context)
                    links_rendered.append(
                        GROUP_LINK.format(link_rendered, link_target, text_rendered)
                    )
            except Exception as e:
                links_rendered.append(
                    '<li><a disabled="disabled" title="{}"><span class="text-muted">'
                    '<i class="fa fa-warning"></i> {}</span></a></li>'.format(
                        e, cl.name
                    )
                )

        if links_rendered:
            template_code += GROUP_BUTTON.format(
                links[0].button_class, group, "".join(links_rendered)
            )

    return mark_safe(template_code)