|
|
@@ -1,3 +1,5 @@
|
|
|
+import difflib
|
|
|
+import re
|
|
|
from collections.abc import Mapping
|
|
|
from copy import deepcopy
|
|
|
from datetime import date, datetime, time, timedelta
|
|
|
@@ -11,6 +13,7 @@ from django.contrib.contenttypes.models import ContentType
|
|
|
from django.core.exceptions import FieldDoesNotExist
|
|
|
from django.db import models
|
|
|
from django.db.models import prefetch_related_objects
|
|
|
+from django.db.models.fields.related_descriptors import ManyToManyDescriptor, ReverseManyToOneDescriptor
|
|
|
from django.utils.datastructures import MultiValueDict
|
|
|
from jinja2.exceptions import TemplateRuntimeError
|
|
|
from netaddr import IPAddress, IPNetwork
|
|
|
@@ -41,6 +44,7 @@ __all__ = (
|
|
|
'RelatedObjectList',
|
|
|
'TemplateObject',
|
|
|
'TemplateObjectList',
|
|
|
+ 'get_missing_field_hint',
|
|
|
'get_query_function',
|
|
|
'get_template_context_data',
|
|
|
'get_template_object',
|
|
|
@@ -70,6 +74,13 @@ _GENERIC_OBJECTS = object()
|
|
|
# Marks a field for which an object has no value (e.g. an object the rendering user may not view)
|
|
|
_MISSING = object()
|
|
|
|
|
|
+# Replacements for names which legacy templates commonly use, but objects don't provide in restricted rendering
|
|
|
+_LEGACY_NAME_HINTS = {
|
|
|
+ 'cf': "Custom field values are under custom_fields (e.g. custom_fields.name).",
|
|
|
+ 'get_absolute_url': "Use display_url for the object's URL.",
|
|
|
+ 'get_config_context': "Use config_context.",
|
|
|
+}
|
|
|
+
|
|
|
|
|
|
def get_template_object(instance, state):
|
|
|
"""
|
|
|
@@ -131,6 +142,21 @@ def get_template_context_data(value):
|
|
|
return value
|
|
|
|
|
|
|
|
|
+def get_missing_field_hint(obj, name):
|
|
|
+ """
|
|
|
+ Return a message explaining why a TemplateObject or list of objects has no attribute with the given name, or None
|
|
|
+ for any other object.
|
|
|
+ """
|
|
|
+ if type(obj) is TemplateObject:
|
|
|
+ return obj._describe_missing(name)
|
|
|
+ if type(obj) in (TemplateObjectList, RelatedObjectList):
|
|
|
+ return (
|
|
|
+ f"A list of objects has no attribute {name!r}. Lists provide all(), count() and first(). Filter them with "
|
|
|
+ f"selectattr() or rejectattr(), or fetch objects with query()."
|
|
|
+ )
|
|
|
+ return None
|
|
|
+
|
|
|
+
|
|
|
def template_json_default(obj):
|
|
|
"""
|
|
|
JSON encoder hook for restricted rendering: TemplateObjects serialize to their full representation.
|
|
|
@@ -244,6 +270,26 @@ class TemplateObject(Mapping):
|
|
|
label = self._model._meta.label if self._model is not None else None
|
|
|
return f'<TemplateObject {label} id={self._data.get("id")!r}>'
|
|
|
|
|
|
+ def _describe_missing(self, name):
|
|
|
+ """
|
|
|
+ Return a message explaining why the object has no field with the given name.
|
|
|
+ """
|
|
|
+ if self._model is None:
|
|
|
+ return None
|
|
|
+ label = self._model._meta.label_lower
|
|
|
+ pk = self._data.get('id')
|
|
|
+ if (batch := self._get_batch()) is not None and pk not in batch.get_instances():
|
|
|
+ return (
|
|
|
+ f"{label} {pk} has no field {name!r}: the rendering user isn't permitted to view this object, so only "
|
|
|
+ f"the fields of its brief representation are available ({', '.join(self._data)})."
|
|
|
+ )
|
|
|
+ message = f"{label} has no field {name!r}."
|
|
|
+ if hint := _get_legacy_name_hint(self._model, name):
|
|
|
+ return f'{message} {hint}'
|
|
|
+ if matches := difflib.get_close_matches(name, _get_field_names(self._model, self._state), n=1):
|
|
|
+ return f'{message} Did you mean {matches[0]!r}?'
|
|
|
+ return message
|
|
|
+
|
|
|
def _get_batch(self):
|
|
|
if self._batch is None and self._model is not None and (pk := self._data.get('id')) is not None:
|
|
|
self._batch = _get_batch(self._model, pk, self._state, self._batches)
|
|
|
@@ -780,6 +826,39 @@ def _get_relations(model):
|
|
|
return relations
|
|
|
|
|
|
|
|
|
+def _get_field_names(model, state):
|
|
|
+ """
|
|
|
+ Return the names of the fields a model's objects provide, including optional reverse relations.
|
|
|
+ """
|
|
|
+ if (serializer_class := _get_serializer_class(model)) is None:
|
|
|
+ return []
|
|
|
+ serializer, fields = _get_serializer(model, state)
|
|
|
+ names = set(fields if fields is not None else serializer.fields)
|
|
|
+ names.update(getattr(serializer_class.Meta, 'optional_fields', ()))
|
|
|
+ return sorted(names)
|
|
|
+
|
|
|
+
|
|
|
+def _get_legacy_name_hint(model, name):
|
|
|
+ """
|
|
|
+ Return a hint for a name which a legacy template might use (e.g. a model method), or None.
|
|
|
+ """
|
|
|
+ if name in _LEGACY_NAME_HINTS:
|
|
|
+ return _LEGACY_NAME_HINTS[name]
|
|
|
+ if match := re.fullmatch(r'get_(\w+)_display', name):
|
|
|
+ return f"Use {match[1]}.label for a choice's label."
|
|
|
+ attribute = getattr(model, name, None)
|
|
|
+ if isinstance(attribute, ReverseManyToOneDescriptor):
|
|
|
+ field = attribute.field
|
|
|
+ related_model = field.related_model if isinstance(field, GenericRelation) else field.model
|
|
|
+ return f"Fetch the related {related_model._meta.label_lower} objects with query()."
|
|
|
+ if isinstance(attribute, ManyToManyDescriptor):
|
|
|
+ related_model = attribute.rel.related_model if attribute.reverse else attribute.rel.model
|
|
|
+ return f"Fetch the related {related_model._meta.label_lower} objects with query()."
|
|
|
+ if callable(attribute) or isinstance(attribute, property):
|
|
|
+ return "Model methods and properties aren't available in restricted rendering."
|
|
|
+ return None
|
|
|
+
|
|
|
+
|
|
|
def _get_choice_fields(model):
|
|
|
"""
|
|
|
Return the names of the serializer fields which represent choices (as {value, label}).
|