Using djoser in Django for token authentication without views

PythonServer Side ProgrammingProgramming

Djoser is a simple authentication library for Django. It is used to generate tokens for authentication; this generated token is generated by taking three fields: username, email and password. It only works on POST request, but you can add its frontend.


Create a Django project and an app. I named them "DjoserExample" and "myapp".

Install two packages −

pip install djoser
pip install djangorestframework

In, add the following lines −

#below every other apps

# Below template variable
   "USER_ID_FIELD": "username"

Here we added djoser and restframework as an app. Then we added authentication backend of REST framework and for djoser, we added the User ID field (i.e., the Index field).

We are using default User Authentication database of Django, so we actually don't need an app.

Go to project's and add the following lines −

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

urlpatterns = [
   path(r'api/v1/', include('djoser.urls')),
   path(r'api/v1/token/login, include('djoser.urls.authtoken'))

Here we defined djoser admin url and then djoser authentication backend.

With that, everything is set. Now run these commands on the terminal and check the output −

python makemigrations
python migrate
python runserver


On −

Here you will create the user.

On −

Here you will generate token for the user by providing username and password.

Published on 26-Aug-2021 13:25:40