apply simple-jwt in django rest framework - DRF
Let’s see /core/urls.py
from django.urls import path, include from home.urls import * from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView, ) urlpatterns = [ path('admin/', admin.site.urls), path('user/',include("home.urls")), path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), ] |
Let’s see, serializers.py
from rest_framework import serializers from django.contrib.auth.models import User from django.contrib.auth.hashers import make_password class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = "__all__" def create(self, validated_data): user = User.objects.create( first_name = validated_data.get("first_name"), last_name = validated_data.get("last_name"), email = validated_data.get("email"), username = validated_data.get("username"), password = make_password(validated_data.get("password")), ) user.save() return user |
Let’s see, views.py
from django.contrib.auth.models import User from rest_framework.response import Response from rest_framework.views import APIView from rest_framework.permissions import IsAuthenticated from rest_framework_simplejwt.authentication import JWTAuthentication from rest_framework_simplejwt.tokens import RefreshToken from .serializers import * class UserRegister(APIView): def post(self,request,format=None): data = request.data user = UserSerializer(data=data) if user.is_valid(raise_exception=True): user.save() # token generation user = User.objects.get(username=data.get("username")) refresh = RefreshToken.for_user(user) return Response({ "message":"user registered successfully!", 'refresh': str(refresh), 'access': str(refresh.access_token), }) else: return Response({ "message":"try again!" }) class UserList(APIView): authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] def get(self,request,format=None): user = User.objects.all() serializer = UserSerializer(user,many=True) return Response({ "user":serializer.data }) |
Let’s see, urls.py
from .views import * urlpatterns=[ path('register/',UserRegister.as_view()), path('allusers/',UserList.as_view()), ] |
Note: if you want user info on the basics of jwt token auth:
class LoginUser(APIView): authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated]
def post(self, request, format=None): data = request.data user = request.user print(data) print('user info: ',user.id) print('user status: ',user.is_superuser) print('user email: ',user.email) return Response({ "message":"user autheticated!", "data":data }) |
output:
<QueryDict: {'name': ['shimanta'], 'email': ['shimanta@microcodes.in']}>
user info: 1
user status: True
user email: admin@mail.com
-------------------------------------------------------------------------------------------------------------------------