adds site display #13735

This commit is contained in:
Abhimanyu Saharan 2023-11-08 22:06:33 +05:30
parent 084a5c5ec8
commit 8b1e18502f
2 changed files with 36 additions and 27 deletions

View File

@ -1,39 +1,50 @@
from django import template from django import template
from django.utils.safestring import mark_safe from django.utils.safestring import mark_safe
from dcim.models import Site
register = template.Library() 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) @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. Renders hierarchical region data for a given object.
""" """
# Check if the obj is an instance of Site # Attempt to retrieve the region from obj or its site attribute
if isinstance(obj, Site): region = getattr(obj, 'region', None) or getattr(getattr(obj, 'site', None), 'region', None)
if not obj.region:
return mark_safe('&mdash;')
# If so, retrieve the Site's Region # Return a placeholder if no region is found
region = obj.region if not region:
else: # If include_site is True, attempt to retrieve the site from obj
if not hasattr(obj, 'site'): if include_site:
return _display_site(obj) or mark_safe('&mdash;')
return mark_safe('&mdash;') return mark_safe('&mdash;')
# Otherwise, retrieve the Region from the Site associated with the object
region = obj.site.region
# Retrieve all regions in the hierarchy # Retrieve all regions in the hierarchy
regions = region.get_ancestors(include_self=True) regions = region.get_ancestors(include_self=True)
# Render the hierarchy as a list of links # Build the URLs and names for the regions
return mark_safe( regions_links = [
' / '.join([
'<a href="{}">{}</a>'.format( '<a href="{}">{}</a>'.format(
context['request'].build_absolute_uri(region.get_absolute_url()), context['request'].build_absolute_uri(region.get_absolute_url()), region
region
) for region in regions ) for region in regions
]) ]
)
# Render the hierarchy as a list of links
region = mark_safe(' / '.join(regions_links))
if include_site:
site = _display_site(obj)
if site:
return mark_safe('{} / {}'.format(region, site))
return region

View File

@ -4,6 +4,7 @@
{% load static %} {% load static %}
{% load plugins %} {% load plugins %}
{% load i18n %} {% load i18n %}
{% load display_region %}
{% block content %} {% block content %}
<div class="row"> <div class="row">
@ -17,10 +18,7 @@
<tr> <tr>
<th scope="row">{% trans "Site" %}</th> <th scope="row">{% trans "Site" %}</th>
<td> <td>
{% if object.site.region %} {% display_region object include_site=True %}
{{ object.site.region|linkify }} /
{% endif %}
{{ object.site|linkify }}
</td> </td>
</tr> </tr>
<tr> <tr>