1👍
The issue you’re encountering is related to how Django processes request bodies and streams.
In Django request.body
is a way to access raw post data.
When you access request.body
, django reads the incoming data and caches it.
This means subsequent accesses to request.body
will not cause any errors, as the data has already been read and stored.
However, when you use request.data
in Django REST Framework, it internally uses a different way to parse the incoming data.
If you access request.data
without accessing it before ( so data hasn’t been read and cached yet), then Django attempts to read from the data stream again.
If the stream has already been read (you read within jwt_views.TokenObtainPairView
), then Django raises the RawPostDataException
error because HTTP data can only be read once.
So can employ following approach to avoid unused variable
@api_view(['POST'])
def signin(request):
data = request.data # Parse and use the request data first
# Create a copy of the request to pass to the TokenObtainPairView
request_copy = request._request
request_copy._data = data
token_view = jwt_views.TokenObtainPairView.as_view()
token_response = token_view(request_copy)
if token_response.status_code == status.HTTP_200_OK:
user = User.objects.filter(username=data['username']).first()
data = {
"access_token": str(token_response.data['access']),
"refresh_token": str(token_response.data['refresh']),
"user_access": {
"is_staff": user.is_staff,
"is_admin": user.is_superuser
}
}
return Response(data, status=status.HTTP_200_OK)
return token_response