Install & Compatibility
Where this runs
tested against v5.0.4 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.920 runs
installs and imports cleanly · install 0.0s · import 0.000s · 70.7MB
glibcpy 3.10–3.920 runs
installs and imports cleanly · install 3.6s · import 0.000s · 71MB
70MB installed
● package 70MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
TokenAuthentication
✓ from knox.auth import TokenAuthentication
✗ from knox.auth import TokenAuthentication
To integrate `django-rest-knox`:
1. Add `knox` to your `INSTALLED_APPS`.
2. Add `knox.auth.TokenAuthentication` to `REST_FRAMEWORK['DEFAULT_AUTHENTICATION_CLASSES']`.
3. Include `knox.urls` in your project's `urls.py`.
4. Optionally, create a custom `LoginView` or use `knox.views.LoginView` directly to handle user login and token creation. The example demonstrates a minimal Django setup with a `LoginView` and a protected endpoint.
import os
import django
from django.conf import settings
from django.urls import path, include
from django.http import JsonResponse
# Minimal Django settings for quickstart
if not settings.configured:
settings.configure(
DEBUG=True,
INSTALLED_APPS=[
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'rest_framework',
'knox',
],
SECRET_KEY=os.environ.get('DJANGO_SECRET_KEY', 'a-very-secret-key-for-dev'),
ROOT_URLCONF=__name__,
DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}},
REST_FRAMEWORK={
'DEFAULT_AUTHENTICATION_CLASSES': [
'knox.auth.TokenAuthentication',
]
},
)
django.setup()
from rest_framework import permissions
from rest_framework.authtoken.views import obtain_auth_token
from knox.views import LoginView as KnoxLoginView, LogoutView, LogoutAllView
from django.contrib.auth.models import User # For example purposes
# Create a dummy user for testing
if not User.objects.filter(username='testuser').exists():
User.objects.create_user(username='testuser', email='test@example.com', password='password123')
def hello_view(request):
return JsonResponse({'message': 'Hello, API!', 'user': str(request.user), 'authenticated': request.user.is_authenticated})
urlpatterns = [
# Knox authentication URLs
path('api/auth/login/', KnoxLoginView.as_view(), name='knox_login'),
path('api/auth/logout/', LogoutView.as_view(), name='knox_logout'),
path('api/auth/logoutall/', LogoutAllView.as_view(), name='knox_logoutall'),
# Protected example view
path('api/hello/', hello_view, name='hello'),
]
# To run:
# 1. Save as a .py file (e.g., quickstart.py)
# 2. python manage.py makemigrations knox (if you create a new project structure)
# 3. python manage.py migrate
# 4. Create a superuser: python manage.py createsuperuser (or use the dummy user created above)
# 5. python manage.py runserver
#
# Test with curl:
# Login (creates token):
# curl -X POST -H "Content-Type: application/json" -d '{"username":"testuser", "password":"password123"}' http://127.0.0.1:8000/api/auth/login/
#
# Access protected endpoint with token (replace YOUR_TOKEN_VALUE):
# curl -H "Authorization: Token YOUR_TOKEN_VALUE" http://127.0.0.1:8000/api/hello/
#
# Logout:
# curl -X POST -H "Authorization: Token YOUR_TOKEN_VALUE" http://127.0.0.1:8000/api/auth/logout/
Debug
Known issues
breakingTokens created prior to django-rest-knox 5.0.0 are no longer valid due to internal changes in token generation and storage.fixUsers will need to log in again to generate new tokens after upgrading to 5.0.0 or later.
affects: <5.0.0
breakingThe `create()` method on the `AuthToken` model changed its signature and return value in 4.0.0. It now returns `(instance, token)` instead of just `token`. Additionally, the `AuthToken` model field `expires` was renamed to `expiry`.fixUpdate any custom code that calls `AuthToken.objects.create()` to expect the new return tuple and adjust references from `expires` to `expiry` on `AuthToken` instances. A migration is required.
affects: <4.0.0
breakingThe `salt` field of the `AuthToken` model was removed in version 4.2.0. This change requires a migration.fixRun `python manage.py makemigrations knox` and `python manage.py migrate` after upgrading to 4.2.0 or later to apply the schema changes correctly.
affects: <4.2.0
gotchaPotential N+1 query issue fixed in 5.0.4 on `AuthToken.user` access. Older versions might suffer performance degradation in scenarios retrieving tokens and accessing their associated users.fixUpgrade to 5.0.4 or later. If unable to upgrade, consider prefetching or selecting related users when querying `AuthToken` objects to mitigate N+1 queries manually.
affects: <5.0.4
gotchaIf `AUTO_REFRESH = True`, tokens could theoretically live forever. Version 5.0.2 introduced `AUTO_REFRESH_MAX_TTL` to limit the total lifetime of such tokens.fixSet `AUTO_REFRESH_MAX_TTL` in your `settings.py` (e.g., `KNOX = {'AUTO_REFRESH_MAX_TTL': timedelta(hours=24)}`) when `AUTO_REFRESH` is enabled to enforce a maximum token lifespan. Ensure you're on version 5.0.2 or newer. affects: <5.0.2 (when AUTO_REFRESH is true)
gotchaA migration issue existed in 5.0.1 when not overriding the `AuthToken` model, which could prevent migrations from running correctly.fixUpgrade to 5.0.2 or later to get the fix for this migration issue.
affects: 5.0.1
Upgrade
Version history
5.0.4latest on PyPI · released Mar 10, 2026
Audit
Dependencies
djangorestframeworkrequiredCore functionality relies on Django REST Framework components.
djangorequiredDjango is the underlying web framework.