from rest_framework import routers, viewsets, serializers from rest_framework.decorators import api_view, permission_classes, authentication_classes from rest_framework.response import Response from rest_framework.authentication import BasicAuthentication from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'first_name', 'last_name') class RegisterUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'password', 'email') extra_kwargs = { 'password': {'write_only': True}, } class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer authentication_classes = [BasicAuthentication] permission_classes = [] @api_view(['GET']) @permission_classes([]) @authentication_classes([BasicAuthentication]) def token(request): return Response({ 'token': request.user.auth_token.key }) @api_view(['POST']) @permission_classes([]) @authentication_classes([]) def registerUser(request): serializer = RegisterUserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() return Response({'username': user.username, 'email': user.email}, status=201) return Response(serializer.errors, status=400) router = routers.SimpleRouter() router.register(r'users', UserViewSet, basename='users') urlpatterns = router.urls