Using djoser in Django for token authentication without views

Djoser is a Django REST authentication library that simplifies token-based authentication. It provides ready-to-use endpoints for user registration, login, and token generation without requiring custom views.

Installation

First, create a Django project and install the required packages ?

pip install djoser
pip install djangorestframework

Django Settings Configuration

Add the required apps and authentication settings to your settings.py ?

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'rest_framework.authtoken',
    'djoser'
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ]
}

DJOSER = {
    "USER_ID_FIELD": "username"
}

URL Configuration

Configure the project's urls.py to include djoser endpoints ?

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/v1/', include('djoser.urls')),
    path('api/v1/', include('djoser.urls.authtoken'))
]

Database Setup

Run migrations to set up the authentication tables ?

python manage.py makemigrations
python manage.py migrate
python manage.py runserver

Available Endpoints

Djoser automatically provides these authentication endpoints:

Endpoint Method Purpose
/api/v1/users/ POST User registration
/api/v1/auth/token/login/ POST Token generation
/api/v1/auth/token/logout/ POST Token invalidation
/api/v1/users/me/ GET Current user profile

Usage Example

User Registration

Send a POST request to /api/v1/users/ with user data:

{
    "username": "testuser",
    "email": "test@example.com",
    "password": "securepassword123"
}

Token Authentication

Send a POST request to /api/v1/auth/token/login/ with credentials:

{
    "username": "testuser",
    "password": "securepassword123"
}

Response will include the authentication token:

{
    "auth_token": "9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b"
}

Key Features

Djoser provides several advantages for Django authentication:

  • No custom views required − All authentication endpoints are pre-built
  • Token-based authentication − Secure stateless authentication
  • RESTful API design − Follows REST principles
  • Customizable settings − Configure user fields and permissions

Conclusion

Djoser simplifies Django REST authentication by providing ready-to-use endpoints for user management and token authentication. It eliminates the need for custom authentication views while maintaining security and flexibility.

Updated on: 2026-03-26T00:49:22+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements