Nick
Nick

Reputation: 674

Delete User from db Django Rest_framework View function

I am pretty new to the django_restframework. I want to be able to delete users from the database when a DELETE request comes in.

Here is my Views:

class RetrieveUsersView(generics.ListCreateAPIView):
  """Retrieves all Users"""
  serializer_class = UserSerializer
  authentication_classes = (authentication.TokenAuthentication,)
  permission_classes = (permissions.IsAuthenticated,)

  queryset = get_user_model().objects.all()

Here is my Serializer:

class UserSerializer(serializers.ModelSerializer):
  """Serializer for the users object"""

  class Meta:
    model = get_user_model()
    fields = ('email', 'password', 'name')
    extra_kwargs = {'password': {'write_only': True, 'min_length': 5}}
  
  def create(self, validated_data):
    """Create a new user with encrypted password and return it"""
    return get_user_model().objects.create_user(**validated_data)

  def update(self, instance, validated_data):
    """Update a user, setting the password correctly and return it"""
    password = validated_data.pop('password', None)
    user = super().update(instance, validated_data)

    if password:
      user.set_password(password)
      user.save()
    
    return user

Here is my Urls:

urlpatterns = [
  path('create/', views.CreateUserView.as_view(), name='create'),
  path('token/', views.CreateTokenView.as_view(), name='token'),
  path('me/', views.ManageUserView.as_view(), name='me'),
  path('all_users/', views.RetrieveUsersView.as_view(), name='all_users')
]

From my understanding Django rest has built in classes that allow DELETE requests. However when I view the api on the local host I am only able to view all the registered users based on my RetrieveUsersView class.

I would expect the url to be something like

/api/users/all_users/1 Then delete that one. I am bit confused on how to get that functionality.

Upvotes: 1

Views: 368

Answers (1)

JPG
JPG

Reputation: 88619

You can make use of the DestroyAPIView which allows you to perform the DELETE operation with ease.

For that, create a new view class as,

class DeleteUserAPI(generics.DestroyAPIView):
    serializer_class = UserSerializer
    authentication_classes = (authentication.TokenAuthentication,)
    permission_classes = (permissions.IsAuthenticated,)
    queryset = get_user_model().objects.all()

and wire this view in your urls.py as,

urlpatterns = [
    path('delete-user/<int:pk>/', views.DeleteUserAPI.as_view(), name='delete-user'),
    # rest of your config
    path('create/', views.CreateUserView.as_view(), name='create'),
    path('token/', views.CreateTokenView.as_view(), name='token'),
    path('me/', views.ManageUserView.as_view(), name='me'),
    path('all_users/', views.RetrieveUsersView.as_view(), name='all_users')
]

Alternatively, you can use the ModelViewSet too to delete the objects.

Upvotes: 1

Related Questions