简体   繁体   English

如何使用序列化程序和通用视图删除 Django 和 DRF 中的用户

[英]How can delete User in Django and DRF using serializers and generic views

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.我正在尝试制作用户 CRUD 功能,我已经制作了其他功能,但无法弄清楚使用 API 删除用户的方法,如果你能提供对代码的审查,那也很好,我做得对吗,并以安全的方式。

Here are the serializers I am using:这是我正在使用的序列化程序:

serializers.py序列化器.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视图.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网址.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我正在学习 Django 和 DRF 所以如果我在这里做错了什么请告诉我,谢谢

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你可以试试这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM