hash password during user registration - without simple JWT
views.py
from rest_framework.response import Response
from rest_framework import status
from core.models import User
from .serializers import *
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework.viewsets import ModelViewSet
class Account(ModelViewSet):
queryset = User.objects.all()
serializer_class = AccountSeralizer
permission_classes = [IsAuthenticated]
authentication_classes = [JWTAuthentication]
def get_permissions(self):
if self.action == "create":
return [AllowAny()]
else:
return [IsAuthenticated()]
def create(self, request):
data = request.data
try:
serializer = self.serializer_class(data=data)
if serializer.is_valid(raise_exception=True):
serializer.save()
return Response({"status": "created"})
else:
return Response(
{"status": "error"},
status=status.HTTP_400_BAD_REQUEST,
)
except Exception as e:
print(e)
return Response({"status": "error"})
--------------------------------------------------------------------------------------------
urls.py
from django.urls import path
from rest_framework.routers import SimpleRouter
from .views import *
router = SimpleRouter()
router.register("",Account)
urlpatterns = [
] + router.urls
------------------------------------------------------------------------------------------
serializers.py
from rest_framework import serializers
from core.models import User
class AccountSeralizer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['first_name','last_name','email','password','address']
extra_kwargs = {"password": {"write_only": True}}
def create(self, validated_data):
password = validated_data.pop("password", None)
instance = super(AccountSeralizer, self).create(validated_data)
if password is not None:
instance.set_password(password)
instance.save()
return instance
def update(self, instance, validated_data):
password = validated_data.pop("password", None)
instance = super(AccountSeralizer, self).update(instance, validated_data)
if password is not None:
instance.set_password(password)
instance.save()
return instance