Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide the token table from the admin panel in Django REST Framework

I'm using Django REST Framework and Django-OAuth-toolkit to enable OAuth2 authentication in my application.

Since after using OAuth2, I no more need token-based authentication and hence no token table/model.

Sometimes it makes me confused after seeing two different modules for handling token.

Therefore, I want to remove/hide Token table from the admin panel of Django.

Here is my settings.py file

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'oauth2_provider.contrib.rest_framework.OAuth2Authentication'
    ),
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated'
    ],
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10
}

I have removed Token based authentication but still Token table is there in the admin panel

enter image description here

like image 518
Anuj TBE Avatar asked Dec 02 '22 11:12

Anuj TBE


2 Answers

You don't have to remove rest_framework.authtoken, you can just kick out its registered admin.

This answer likely doesn't apply to you but if you want to carry on using authtokens and just make them hidden from the Admin, you can add the following to one of your existing admin.py files:

try:
    from rest_framework.authtoken.models import TokenProxy as DRFToken
except ImportError:
    from rest_framework.authtoken.models import Token as DRFToken

admin.site.unregister(DRFToken)

Why the ugly code? It's to cope with a 2020 edit whereby the ModelAdmin used here is registered against a proxy model to another which picks the User's PK as its main primary key (for URLs, etc) rather than the database ID of the Token. These are one-to-one mapped, so it makes some sense.

If you know you're only supporting DRF 3.12.0 and newer, you can hack this down to TokenProxy.

like image 73
Oli Avatar answered Jan 15 '23 15:01

Oli


from rest_framework.authtoken.models import TokenProxy
admin.site.unregister(TokenProxy)
like image 22
Ahmed Safadi Avatar answered Jan 15 '23 17:01

Ahmed Safadi