Reputation: 25
I am trying to make user CRUD functions, I have made other functions but can't figure out the way to delete the user using the API, It will be also great if you can provide a review on the code, am I doing it correctly, and in safe way.
Here are the serializers I am using:
serializers.py
from .models import User
class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(
max_length=128,
min_length=8,
write_only=True
)
class Meta:
model = User
fields = ('email', 'password', 'first_name', 'last_name')
extra_kwargs = {
'password': {'write_only': True},
'first_name': {'required': True},
'last_name': {'required': True},
}
def create(self, validated_data):
user = User(
email = validated_data['email'],
first_name = validated_data['first_name'],
last_name = validated_data['last_name']
)
user.set_password(validated_data['password'])
user.save()
return user
class UpdateUserSerializer(serializers.ModelSerializer):
email = serializers.EmailField(required=True)
class Meta:
model = User
fields = ('first_name', 'last_name', 'email')
extra_kwargs = {
'first_name': {'required': True},
'last_name': {'required': True},
}
def validate_email(self, value):
user = self.context['request'].user
if User.objects.exclude(pk=user.pk).filter(email=value).exists():
raise serializers.ValidationError({"email": "This email is already in use."})
return value
def update(self, instance, validated_data):
user = self.context['request'].user
if user.pk != instance.pk:
raise serializers.ValidationError({"authorize": "You dont have permission for this user."})
instance.first_name = validated_data['first_name']
instance.last_name = validated_data['last_name']
instance.email = validated_data['email']
instance.save()
return instance
views.py
from rest_framework import generics
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django.contrib.auth import get_user_model
from .serializers import UserSerializer, UpdateUserSerializer, ChangePasswordSerializer
# Create your views here.
class UserCreate(generics.CreateAPIView):
authentication_classes = ()
permission_classes = ()
serializer_class = UserSerializer
class ChangePasswordView(generics.UpdateAPIView):
User = get_user_model()
queryset = User.objects.all()
permission_classes = (IsAuthenticated,)
serializer_class = ChangePasswordSerializer
class UpdateUserView(generics.UpdateAPIView):
User = get_user_model()
queryset = User.objects.all()
permission_classes = (IsAuthenticated,)
serializer_class = UpdateUserSerializer
class HelloView(APIView):
permission_classes = (IsAuthenticated, )
def get(self, request):
content = {'message':'Hello World!'}
return Response(content)
urls.py
from django.urls import path
from rest_framework_simplejwt import views
from .views import (
UserCreate,
UpdateUserView,
ChangePasswordView,
HelloView
)
urlpatterns = [
path('create/', UserCreate.as_view(), name='user_create'),
path('token/', views.TokenObtainPairView.as_view(), name='token_optain_pair'),
path('token/refresh/', views.TokenRefreshView.as_view(), name='token_refresh'),
path('hello/', HelloView.as_view(), name='hello'),
path('update/<int:pk>/', UpdateUserView.as_view(), name='update_user'),
path('change_password/<int:pk>/', ChangePasswordView.as_view(), name='auth_change_password'),
]
I am learning Django and DRF so please let me know if I am doing any thing wrong here, thanks
Upvotes: 0
Views: 468
Reputation: 464
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = '__all__'
class UserDeleteApi(generics.DestroyAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
path('api/<int:pk>/delete',UserDeleteApi.as_view())
You Can try this way
Upvotes: 1