Problem : I am trying to make a request of type PUT
to modify data of one API REST
in django
, but once the method PUT
inside is configured views.py
when making the request I get the following error message in the browser console:
Access to XMLHttpRequest at 'http://localhost:8000/api/Players/0' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
Views.py
@api_view(['PUT'])
def api_update_jugadores(request, slug):
try:
usuario_var = USUARIO.objects.get(slug = slug)
except USUARIO.DoesNotExist:
return Response(status = status.HTTP_404_NOT_FOUND)
if request.method == 'PUT':
serializer = UsuariosSerializer(usuario_var, data = request.data)
data = {}
if serializer.is_valid():
serializer.save()
data['success'] = 'update successful'
return Response(data=data)
return Response(serializer.errors, status = status.HTTP_BAD_REQUEST)
class UsuarioView(viewsets.ModelViewSet):
search_fields = ['nombre']
filter_backends = (filters.SearchFilter,)
serializer_class = UsuariosSerializer
queryset = USUARIO.objects.all()
Request code
async buttonHandler(jugador) {
const url = 'http://localhost:8000/api/Jugadores/' + jugador.id;
jugador.usuario_equipo = 2;
await axios.put(url, jugador);
}
As they fix it here , try:
Install the necessary cors packages:
Add it to your installed apps in ``setting.py`:
Also add it in MIDDLEWARE, it should be at the beginning of this list :
Add this setting before INSTALLED_APPS:
Or, alternatively, create a list of all possible endpoints :