This commit is contained in:
Abhimanyu Saharan 2023-11-08 22:08:56 +05:30
parent 8b1e18502f
commit 28fc6555ef

View File

@ -3,48 +3,35 @@ from django.utils.safestring import mark_safe
register = template.Library() register = template.Library()
def _display_site(obj): def _display_site(obj):
""" """
Render a link to the site of an object. Render a link to the site of an object.
""" """
if hasattr(obj, 'site'): site = getattr(obj, 'site', None)
return mark_safe('<a href="{}">{}</a>'.format( return mark_safe('<a href="{}">{}</a>'.format(site.get_absolute_url(), site)) if site else None
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, include_site=False): def display_region(context, obj, include_site=False):
""" """
Renders hierarchical region data for a given object. Renders hierarchical region data for a given object, optionally including the site.
""" """
# Attempt to retrieve the region from obj or its site attribute # Retrieve the region or site information
region = getattr(obj, 'region', None) or getattr(getattr(obj, 'site', None), 'region', None) region = getattr(obj, 'region', None) or getattr(obj.site, 'region', None) if hasattr(obj, 'site') else None
site_link = _display_site(obj) if include_site else None
# Return a placeholder if no region is found # Return a placeholder if no region or site is found
if not region: if not region and not site_link:
# 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;') return mark_safe('&mdash;')
# Retrieve all regions in the hierarchy # Build the region links if the region is available
regions = region.get_ancestors(include_self=True) region_links = ' / '.join(
'<a href="{}">{}</a>'.format(context['request'].build_absolute_uri(reg.get_absolute_url()), reg)
for reg in region.get_ancestors(include_self=True)
) if region else ''
# Build the URLs and names for the regions # Concatenate region and site links
regions_links = [ links = ' / '.join(filter(None, [region_links, site_link]))
'<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(links)
region = mark_safe(' / '.join(regions_links))
if include_site:
site = _display_site(obj)
if site:
return mark_safe('{} / {}'.format(region, site))
return region