Djoser Setup Guide for Django Rest Framework
Djoser is a third-party package developed by SUNSCRAPERS for handling authentication in Django Rest Framework (DRF). It provides a set of views to manage essential actions like Login, Logout, Password Reset, and Account Activation.
Requirements for Djoser Setup
Ensure the following versions of Python, Django, and Django Rest Framework (DRF) are installed:
- Python:
3.7
,3.8
,3.9
,3.10
(Must be>= 3.7
) - Django:
2.2
,3.1
,3.2
,4.0
- Django Rest Framework:
3.11.1
,3.12.1
,3.13
If you need to support older versions, use Djoser < 2.2.
Installation
Activate your virtual environment and install Djoser using pip
:
pip install djoser
If you want to use JWT authentication, you also need to install that with simply code in the terminal.
pip install djangorestframework_simplejwt
Lastly, if you need social-auth i.e. third party based authentication i.e. facebook, you will need to install by one line in terminal below.
pip install social-auth-app-django
If you have completed that then lets start the configuration part. In the configuration part we just need to edit settings.py file of the django project where we need to add in INSTALLED APP.
INSTALLED_APPS = (
'django.contrib.auth',
(...),
'rest_framework',
'djoser',
(...),
)
And in urls.py of the project name, just add urls of djoser. It looks something like this.
urlpatterns = [
(...),
path('auth/', include('djoser.urls')),
path('auth/', include('djoser.urls.jwt')),
]
Now let’s setup default authentication in setting.py file
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
(...)
),
}
Also, configure django-rest-framework-simplejwt to use the Authorization: JWT ACCESS TOKEN header in settings.py file.
SIMPLE_JWT = {
'AUTH_HEADER_TYPES': ('JWT',),
}
So, we have JSON web tokens set up as our default authentication scheme so it’s as easy as that and now we can kind a deal with the rest of these settings so other settings we’re gonna need.
DJOSER = {
'LOGIN_FIELD': 'email',
'USER_CREATE_PASSWORD_RETYPE': True,
'USERNAME_CHANGED_EMAIL_CONFIRMATION': True
'PASSWORD_RESET_CONFIRM_URL':
'#/password/reset/confirm/{uid}/{token}',
'USERNAME_RESET_CONFIRM_URL':
'#/username/reset/confirm/{uid}/{token}',
'ACTIVATION_URL': '#/activate/{uid}/{token}',
'SEND_ACTIVATION_EMAIL': True,
'SERIALIZERS': {},
}
So, above code shows, our main login field is email and when we create a user I want them to be required to retype their passwords, so we have this user create password retype to True. Another thing I’m gonna use is username changed confirmation where if True then it changes username endpoints will send confirmation email to user. And another one is Password Reset Confirm Url, Username Change Confirmation Url and so on.
Thus with these configuration we can use the Djoser Package which makes us easier. Hope you enjoy the section.