The admin interface cannot input Entity
Describe the bug When using the default user model The management interface cannot input entities. Did I configure it incorrectly, but I followed the quick start execution
Expected behavior It should be possible to select or create entities. Just like other foreign keys
Screenshots
As shown in the figure, Entity cannot be operated
Desktop (please complete the following information):
- OS: win 10
- Python Version: 3.12
- Django Version: 5.1.6
- DRF Version: 3.15.2
It happens because the "entity" field is read only on admin.py file.
Thanks, after rewriting the get_readonly_fields function in admin.py, I can use it now!
So adding sth to the Entity field is absolutely needed in order to create an API key, is this correct? When trying to save the API key entry without entity, I geht the following exception:
django.db.utils.IntegrityError: null value in column "entity_id" of relation "drf_simple_apikey_apikey" violates not-null constraint
What is the meaning of the Entity field? I've seen it in the docs but it seems that I need more knowledge to use it. Is it just a human-readable name in order to document what the API key shall be used for?
Ah okay, I see, it's a foreign key to a user.
This is the workaround I'm using now, placed in an own admin.py file of my project:
from drf_simple_apikey.admin import ApiKeyAdmin
from drf_simple_apikey.models import APIKey
class MyApiKeyAdmin(ApiKeyAdmin):
def get_readonly_fields(
self, request: HttpRequest, obj: APIKey = None
) -> typing.Tuple[str, ...]:
return ["created"]
admin.site.unregister(APIKey)
admin.site.register(APIKey, MyApiKeyAdmin)
I fix this by checking if the object is not None when the object is being edited Which means the entity will be editable when creation
drf_simple_apikey/admin.py
def get_readonly_fields(
self, request: HttpRequest, obj: APIKey = None
) -> typing.Tuple[str, ...]:
fields = ("created",)
if obj is not None:
fields += ("entity",)
if obj and obj.revoked:
fields += (
"name",
"revoked",
"expiry_date",
)
return fields
Nice discussion there. This might be a design issue. The Entity field is a ForeignKey that defines which model the APIKey is linked to.
I forgot why the Entity field is only in read mode, but I'll investigate and see if there is a fix. In the meantime, @king-ppap is a great workaround I believe.