passing related objects through messages rather than through extra_context

This commit is contained in:
David Kennedy 2024-01-19 11:33:45 -05:00
parent 83c34ceaf0
commit cbd19b65fe
No known key found for this signature in database
GPG key ID: 6528A5386E66B96B
3 changed files with 14 additions and 38 deletions

View file

@ -20,6 +20,7 @@ from . import models
from auditlog.models import LogEntry # type: ignore from auditlog.models import LogEntry # type: ignore
from auditlog.admin import LogEntryAdmin # type: ignore from auditlog.admin import LogEntryAdmin # type: ignore
from django_fsm import TransitionNotAllowed # type: ignore from django_fsm import TransitionNotAllowed # type: ignore
from django.utils.safestring import mark_safe
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -415,7 +416,6 @@ class ContactAdmin(ListHeaderAdmin):
"contact", "contact",
"email", "email",
] ]
change_form_template = "django/admin/contact_change_form.html"
# We name the custom prop 'contact' because linter # We name the custom prop 'contact' because linter
# is not allowing a short_description attr on it # is not allowing a short_description attr on it
@ -456,8 +456,7 @@ class ContactAdmin(ListHeaderAdmin):
def change_view(self, request, object_id, form_url='', extra_context=None): def change_view(self, request, object_id, form_url='', extra_context=None):
"""Extend the change_view for Contact objects in django admin. """Extend the change_view for Contact objects in django admin.
Customize to display related objects to the Contact. These will be passed Customize to display related objects to the Contact. These will be passed
through the extra_context to the template for display to the user.""" through the messages construct to the template for display to the user."""
extra_context = extra_context or {}
# Fetch the Contact instance # Fetch the Contact instance
contact = models.Contact.objects.get(pk=object_id) contact = models.Contact.objects.get(pk=object_id)
@ -471,12 +470,14 @@ class ContactAdmin(ListHeaderAdmin):
# Check if the related field is not None # Check if the related field is not None
related_manager = getattr(contact, related_field.name) related_manager = getattr(contact, related_field.name)
if related_manager is not None: if related_manager is not None:
# Check if it's a ManyToManyField or a reverse ForeignKey/OneToOneField # Check if it's a ManyToManyField/reverse ForeignKey or a OneToOneField
# Do this by checking for a method on the related_manager # Do this by checking for get_queryset method on the related_manager
if hasattr(related_manager, 'get_queryset'): if hasattr(related_manager, 'get_queryset'):
# Handles ManyToManyRel and ManyToOneRel
queryset = related_manager.get_queryset() queryset = related_manager.get_queryset()
else: else:
queryset = related_manager.all() # Handles OneToOne rels, ie. User
queryset = [related_manager]
for obj in queryset: for obj in queryset:
# for each object, build the edit url in this view and add as tuple # for each object, build the edit url in this view and add as tuple
@ -487,9 +488,13 @@ class ContactAdmin(ListHeaderAdmin):
change_url = reverse('admin:%s_%s_change' % (app_label, model_name), args=[obj_id]) change_url = reverse('admin:%s_%s_change' % (app_label, model_name), args=[obj_id])
related_objects.append((change_url, obj)) related_objects.append((change_url, obj))
# set the related_objects array in extra_context if related_objects:
extra_context['related_objects'] = related_objects message = f"<h2>Related Objects:</h2><ul>"
for url, obj in related_objects:
message += f"<li>{obj.__class__.__name__}: <a href='{url}'>{obj}</a></li>"
message += "</ul>"
message_html = mark_safe(message)
messages.warning(request, message_html,)
return super().change_view(request, object_id, form_url, extra_context=extra_context) return super().change_view(request, object_id, form_url, extra_context=extra_context)

View file

@ -1,24 +0,0 @@
{% extends 'admin/change_form.html' %}
{% load custom_filters %}
{% block content %}
{% if related_objects %}
<div>
<h2>Related Objects:</h2>
<ul>
{% for url, obj in related_objects %}
<li>
{{ obj|class_name }}:
<a href="{{ url }}">
{{ obj }}
</a>
</li>
{% endfor %}
</ul>
</div>
{% endif %}
{{ block.super }}
{% endblock %}

View file

@ -7,11 +7,6 @@ register = template.Library()
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@register.filter
def class_name(value):
return value.__class__.__name__
@register.filter(name="extract_value") @register.filter(name="extract_value")
def extract_value(html_input): def extract_value(html_input):
match = re.search(r'value="([^"]*)"', html_input) match = re.search(r'value="([^"]*)"', html_input)