Skip to content

Commit

Permalink
adds site display #13735
Browse files Browse the repository at this point in the history
  • Loading branch information
abhi1693 committed Nov 8, 2023
1 parent 084a5c5 commit 8b1e185
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 27 deletions.
57 changes: 34 additions & 23 deletions netbox/dcim/templatetags/display_region.py
Original file line number Diff line number Diff line change
@@ -1,39 +1,50 @@
from django import template
from django.utils.safestring import mark_safe

from dcim.models import Site

register = template.Library()

def _display_site(obj):
"""
Render a link to the site of an object.
"""
if hasattr(obj, 'site'):
return mark_safe('<a href="{}">{}</a>'.format(
obj.site.get_absolute_url(),
obj.site
))
return None


@register.simple_tag(takes_context=True)
def display_region(context, obj):
def display_region(context, obj, include_site=False):
"""
Renders hierarchical region data for a given object.
"""
# Check if the obj is an instance of Site
if isinstance(obj, Site):
if not obj.region:
return mark_safe('&mdash;')
# Attempt to retrieve the region from obj or its site attribute
region = getattr(obj, 'region', None) or getattr(getattr(obj, 'site', None), 'region', None)

# If so, retrieve the Site's Region
region = obj.region
else:
if not hasattr(obj, 'site'):
return mark_safe('&mdash;')

# Otherwise, retrieve the Region from the Site associated with the object
region = obj.site.region
# Return a placeholder if no region is found
if not region:
# If include_site is True, attempt to retrieve the site from obj
if include_site:
return _display_site(obj) or mark_safe('&mdash;')
return mark_safe('&mdash;')

# Retrieve all regions in the hierarchy
regions = region.get_ancestors(include_self=True)

# Build the URLs and names for the regions
regions_links = [
'<a href="{}">{}</a>'.format(
context['request'].build_absolute_uri(region.get_absolute_url()), region
) for region in regions
]

# Render the hierarchy as a list of links
return mark_safe(
' / '.join([
'<a href="{}">{}</a>'.format(
context['request'].build_absolute_uri(region.get_absolute_url()),
region
) for region in regions
])
)
region = mark_safe(' / '.join(regions_links))
if include_site:
site = _display_site(obj)
if site:
return mark_safe('{} / {}'.format(region, site))

return region
6 changes: 2 additions & 4 deletions netbox/templates/dcim/rack.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
{% load static %}
{% load plugins %}
{% load i18n %}
{% load display_region %}

{% block content %}
<div class="row">
Expand All @@ -17,10 +18,7 @@ <h5 class="card-header">
<tr>
<th scope="row">{% trans "Site" %}</th>
<td>
{% if object.site.region %}
{{ object.site.region|linkify }} /
{% endif %}
{{ object.site|linkify }}
{% display_region object include_site=True %}
</td>
</tr>
<tr>
Expand Down

0 comments on commit 8b1e185

Please sign in to comment.