This commit is contained in:
David Kennedy 2023-12-15 17:05:26 -05:00
parent 3073dd98f2
commit 75d5a951d7
No known key found for this signature in database
GPG key ID: 6528A5386E66B96B
3 changed files with 20 additions and 100 deletions

View file

@ -45,22 +45,32 @@ class CustomLogEntryAdmin(LogEntryAdmin):
add_form_template = "admin/change_form_no_submit.html" add_form_template = "admin/change_form_no_submit.html"
class AdminSortFields(): class AdminSortFields:
def get_queryset(db_field): def get_queryset(db_field):
"""This is a helper function for formfield_for_manytomany and formfield_for_foreignkey""" """This is a helper function for formfield_for_manytomany and formfield_for_foreignkey"""
logger.info(f"getting queryset for {db_field.name}") logger.info(f"getting queryset for {db_field.name}")
# customize sorting # customize sorting
if db_field.name in ("other_contacts", "authorizing_official", "submitter",): if db_field.name in (
"other_contacts",
"authorizing_official",
"submitter",
):
# Sort contacts by first_name, then last_name, then email # Sort contacts by first_name, then last_name, then email
return models.Contact.objects.all().order_by(Concat("first_name","last_name","email")) return models.Contact.objects.all().order_by(Concat("first_name", "last_name", "email"))
elif db_field.name in ("current_websites", "alternative_domains"): elif db_field.name in ("current_websites", "alternative_domains"):
# sort web sites # sort web sites
return models.Website.objects.all().order_by("website") return models.Website.objects.all().order_by("website")
elif db_field.name in ("creator", "user", "investigator",): elif db_field.name in (
"creator",
"user",
"investigator",
):
# Sort users by first_name, then last_name, then email # Sort users by first_name, then last_name, then email
return models.User.objects.all().order_by(Concat("first_name","last_name","email")) return models.User.objects.all().order_by(Concat("first_name", "last_name", "email"))
elif db_field.name in ("domain", "approved_domain",): elif db_field.name in (
"domain",
"approved_domain",
):
# Sort domains by name # Sort domains by name
return models.Domain.objects.all().order_by("name") return models.Domain.objects.all().order_by("name")
elif db_field.name in ("requested_domain",): elif db_field.name in ("requested_domain",):
@ -85,7 +95,7 @@ class AuditedAdmin(admin.ModelAdmin):
object_id=object_id, object_id=object_id,
) )
) )
def formfield_for_manytomany(self, db_field, request, **kwargs): def formfield_for_manytomany(self, db_field, request, **kwargs):
"""customize the behavior of formfields with manytomany relationships. the customized """customize the behavior of formfields with manytomany relationships. the customized
behavior includes sorting of objects in lists as well as customizing helper text""" behavior includes sorting of objects in lists as well as customizing helper text"""
@ -99,7 +109,7 @@ class AuditedAdmin(admin.ModelAdmin):
+ " If more than one value is selected, the change/delete/view actions will be disabled." + " If more than one value is selected, the change/delete/view actions will be disabled."
) )
return formfield return formfield
def formfield_for_foreignkey(self, db_field, request, **kwargs): def formfield_for_foreignkey(self, db_field, request, **kwargs):
"""customize the behavior of formfields with foreign key relationships. this will customize """customize the behavior of formfields with foreign key relationships. this will customize
the behavior of selects. customized behavior includes sorting of objects in list""" the behavior of selects. customized behavior includes sorting of objects in list"""
@ -809,7 +819,7 @@ class DomainInformationInline(admin.StackedInline):
+ " If more than one value is selected, the change/delete/view actions will be disabled." + " If more than one value is selected, the change/delete/view actions will be disabled."
) )
return formfield return formfield
def formfield_for_foreignkey(self, db_field, request, **kwargs): def formfield_for_foreignkey(self, db_field, request, **kwargs):
"""customize the behavior of formfields with foreign key relationships. this will customize """customize the behavior of formfields with foreign key relationships. this will customize
the behavior of selects. customized behavior includes sorting of objects in list""" the behavior of selects. customized behavior includes sorting of objects in list"""

View file

@ -1,63 +0,0 @@
import logging
from typing import Dict
from django.forms import ModelChoiceField
logger = logging.getLogger(__name__)
class SortingDict:
"""Stores a sorting dictionary object"""
_sorting_dict: Dict[type, type] = {}
def __init__(self, model_list, sort_list):
self._sorting_dict = {
"dropDownSelected": self.convert_list_to_dict(model_list),
"sortBy": sort_list,
}
# Used in __init__ for model_list for performance reasons
def convert_list_to_dict(self, value_list):
"""Used internally to convert model_list to a dictionary"""
return {item: item for item in value_list}
def get_dict(self):
"""Grabs the associated dictionary item,
has two fields: 'dropDownSelected': model_list and 'sortBy': sort_list"""
# This should never happen so we need to log this
if self._sorting_dict is None:
raise ValueError("_sorting_dict was None")
return self._sorting_dict
class AdminFormOrderHelper:
"""A helper class to order a dropdown field in Django Admin,
takes the fields you want to order by as an array"""
# Used to keep track of how we want to order_by certain FKs
_sorting_list: list[SortingDict] = []
def __init__(self, sort: list[SortingDict]):
self._sorting_list = sort
def get_ordered_form_field(self, form_field, db_field) -> ModelChoiceField | None:
"""Orders the queryset for a ModelChoiceField
based on the order_by_dict dictionary"""
_order_by_list = []
for item in self._sorting_list:
item_dict = item.get_dict()
drop_down_selected = item_dict.get("dropDownSelected")
sort_by = item_dict.get("sortBy")
if db_field.name in drop_down_selected:
_order_by_list = sort_by
# Exit loop when order_by_list is found
break
# Only order if we choose to do so
# noqa for the linter... reduces readability otherwise
if _order_by_list is not None and _order_by_list != []: # noqa
form_field.queryset = form_field.queryset.order_by(*_order_by_list)
return form_field

View file

@ -1,27 +0,0 @@
from registrar.models.utility.admin_form_order_helper import (
AdminFormOrderHelper,
SortingDict,
)
class AdminSortFields:
# Used to keep track of how we want to order_by certain FKs
foreignkey_orderby_dict: list[SortingDict] = [
# foreign_key - order_by
# Handles fields that are sorted by 'first_name / last_name
SortingDict(
["submitter", "authorizing_official", "investigator", "creator", "user"],
["first_name", "last_name"],
),
# Handles fields that are sorted by 'name'
SortingDict(["domain", "requested_domain"], ["name"]),
SortingDict(["domain_application"], ["requested_domain__name"]),
]
# For readability purposes, but can be replaced with a one liner
def form_field_order_helper(self, form_field, db_field):
"""A shorthand for AdminFormOrderHelper(foreignkey_orderby_dict)
.get_ordered_form_field(form_field, db_field)"""
form = AdminFormOrderHelper(self.foreignkey_orderby_dict)
return form.get_ordered_form_field(form_field, db_field)