initial work to render hierarchical region #13735

This commit is contained in:
Abhimanyu Saharan 2023-11-08 21:56:50 +05:30
parent 22e474ff96
commit 084a5c5ec8
4 changed files with 43 additions and 16 deletions

View File

View File

@ -0,0 +1,39 @@
from django import template
from django.utils.safestring import mark_safe
from dcim.models import Site
register = template.Library()
@register.simple_tag(takes_context=True)
def display_region(context, obj):
"""
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('—')
# If so, retrieve the Site's Region
region = obj.region
else:
if not hasattr(obj, 'site'):
return mark_safe('—')
# Otherwise, retrieve the Region from the Site associated with the object
region = obj.site.region
# Retrieve all regions in the hierarchy
regions = region.get_ancestors(include_self=True)
# 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
])
)

View File

@ -5,6 +5,7 @@
{% load helpers %} {% load helpers %}
{% load plugins %} {% load plugins %}
{% load i18n %} {% load i18n %}
{% load display_region %}
{% block content %} {% block content %}
<div class="row"> <div class="row">
@ -16,14 +17,7 @@
<tr> <tr>
<th scope="row">{% trans "Region" %}</th> <th scope="row">{% trans "Region" %}</th>
<td> <td>
{% if object.site.region %} {% display_region object %}
{% for region in object.site.region.get_ancestors %}
{{ region|linkify }} /
{% endfor %}
{{ object.site.region|linkify }}
{% else %}
{{ ''|placeholder }}
{% endif %}
</td> </td>
</tr> </tr>
<tr> <tr>

View File

@ -3,6 +3,7 @@
{% load plugins %} {% load plugins %}
{% load tz %} {% load tz %}
{% load i18n %} {% load i18n %}
{% load display_region %}
{% block breadcrumbs %} {% block breadcrumbs %}
{{ block.super }} {{ block.super }}
@ -29,14 +30,7 @@
<tr> <tr>
<th scope="row">{% trans "Region" %}</th> <th scope="row">{% trans "Region" %}</th>
<td> <td>
{% if object.region %} {% display_region object %}
{% for region in object.region.get_ancestors %}
{{ region|linkify }} /
{% endfor %}
{{ object.region|linkify }}
{% else %}
{{ ''|placeholder }}
{% endif %}
</td> </td>
</tr> </tr>
<tr> <tr>