1from django.contrib.auth.models import User
2from django.shortcuts import get_object_or_404
3from myapps.serializers import UserSerializer
4from rest_framework import viewsets
5from rest_framework.response import Response
6
7class UserViewSet(viewsets.ViewSet):
8 """
9 A simple ViewSet for listing or retrieving users.
10 """
11 def list(self, request):
12 queryset = User.objects.all()
13 serializer = UserSerializer(queryset, many=True)
14 return Response(serializer.data)
15
16 def retrieve(self, request, pk=None):
17 queryset = User.objects.all()
18 user = get_object_or_404(queryset, pk=pk)
19 serializer = UserSerializer(user)
20 return Response(serializer.data)
1def perform_update(self, serializer):
2 # Save with the new value for the target model fields
3 user = self.request.user
4 userid = str(user.id)
5 serializer.save(stu_enrolled_classes=userid)
6# The above def is in viewset and you can specify what field else can be edited in the API "PUT",
7# Here We just set the stu_enrolled_classes field with is relation to the user to be the current user that send the "PUT" request.