Skip to content
This repository has been archived by the owner on Dec 18, 2023. It is now read-only.

Commit

Permalink
fix(backend):Add Error 409 username already exists
Browse files Browse the repository at this point in the history
Signed-off-by: raumonmar1 <raumonmar1@alum.us.es>
  • Loading branch information
raumonmar1 authored and ferferga committed Dec 13, 2023
1 parent 2cfc667 commit dc1e220
Showing 1 changed file with 12 additions and 0 deletions.
12 changes: 12 additions & 0 deletions backend/TraineerbookApp/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,11 +92,18 @@ class RegisterUserView(APIView):
responses={
200: OpenApiResponse(response=None),
400: OpenApiResponse(response=None, description="Los datos de la petición son incorrectos"),
409: OpenApiResponse(response=None, description="El nombre de usuario ya existe")
}
)
def post(self, request):
serializer = UserSerializer(data=request.data)
if serializer.is_valid():
username = request.data.get('username')

# Verificar si el nombre de usuario ya existe
if User.objects.filter(username=username).exists():
return Response({"error": "El nombre de usuario ya existe"}, status=status.HTTP_409_CONFLICT)

# Crear el usuario y establecer la contraseña sin guardarlo inmediatamente
user = serializer.save()

Expand All @@ -108,6 +115,11 @@ def post(self, request):
login(request, user)

return Response(status=status.HTTP_200_OK)

# Verificar específicamente si el error es debido al nombre de usuario duplicado
if 'username' in serializer.errors and 'Ya existe un usuario con este nombre.' in serializer.errors['username']:
return Response({"error": "El nombre de usuario ya existe"}, status=status.HTTP_409_CONFLICT)

return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class LoginView(APIView):
Expand Down

0 comments on commit dc1e220

Please sign in to comment.