Opened 5 hours ago
Last modified 3 hours ago
#36804 assigned Cleanup/optimization
AdminSite.get_model_admin raises AttributeError when `to` model of a ForeignKey is defined as a string
| Reported by: | Parth Paradkar | Owned by: | Parth Paradkar |
|---|---|---|---|
| Component: | contrib.admin | Version: | 5.2 |
| Severity: | Normal | Keywords: | admin |
| Cc: | Parth Paradkar | Triage Stage: | Accepted |
| Has patch: | no | Needs documentation: | no |
| Needs tests: | no | Patch needs improvement: | no |
| Easy pickings: | yes | UI/UX: | no |
Description
I have a foreign key on one of my models defined as-
slack_alert = models.ForeignKey(
"falcon.SlackAlert",
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name="tickets",
)
When I do not include the falcon app in INSTALLED_APPS, the admin site raises an error (which is expected). However, while handling the expected KeyError, it throws an AttributeError. I am guessing this is since it expects a Model instance.
Traceback-
Traceback (most recent call last):
File "/Users/parthparadkar/projects/lighthouse/venv/lib/python3.11/site-packages/django/contrib/admin/sites.py", line 170, in get_model_admin
return self._registry[model]
~~~~~~~~~~~~~~^^^^^^^
KeyError: 'falcon.SlackAlert'
During handling of the above exception, another exception occurred:
File "/Users/parthparadkar/projects/lighthouse/venv/lib/python3.11/site-packages/django/contrib/admin/checks.py", line 209, in _check_autocomplete_fields
[
File "/Users/parthparadkar/projects/lighthouse/venv/lib/python3.11/site-packages/django/contrib/admin/checks.py", line 210, in <listcomp>
self._check_autocomplete_fields_item(
File "/Users/parthparadkar/projects/lighthouse/venv/lib/python3.11/site-packages/django/contrib/admin/checks.py", line 239, in _check_autocomplete_fields_item
related_admin = obj.admin_site.get_model_admin(field.remote_field.model)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/parthparadkar/projects/lighthouse/venv/lib/python3.11/site-packages/django/contrib/admin/sites.py", line 172, in get_model_admin
raise NotRegistered(f"The model {model.__name__} is not registered.")
^^^^^^^^^^^^^^
AttributeError: 'str' object has no attribute '__name__'. Did you mean: '__ne__'?
I think this can be fixed by checking with isinstance before raising NotRegistered?
except KeyError:
if isinstance(model, str):
raise NotRegistered(f"The model {model} is not registered.")
else:
raise NotRegistered(f"The model {model.__name__} is not registered.")
Change History (2)
comment:1 by , 3 hours ago
| Triage Stage: | Unreviewed → Accepted |
|---|---|
| Type: | Bug → Cleanup/optimization |
comment:2 by , 3 hours ago
| Owner: | set to |
|---|---|
| Status: | new → assigned |
Note:
See TracTickets
for help on using tickets.
Thanks. I'd suggest
{model!r}instead of{model}but otherwise LGTM.