Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AuthTokenSerializer. Invalid data. Expected a dictionary, but got Request. Django

Tags:

python

django

Sorry for my english. I have learning django rest and i want create token authorization. I did it by tutorial, but i have error, when send data to server

{
    "non_field_errors": [
        "Invalid data. Expected a dictionary, but got Request."
    ]
}

my setting file:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'rest_framework.authtoken',

    'users',
]

..

..
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',),
    'PAGE_SIZE': 10,
     'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    )
}

my url

urlpatterns = [
    url(r'^authtoken', views.ObtainAuthToken.as_view()),
]

my view

class ObtainAuthToken(APIView):
    permission_classes = (permissions.AllowAny,)
    serializer_class = AuthTokenSerializer

    def post(self, request):
        serializer = self.serializer_class(data=request)
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        token, created = Token.objects.get_or_create(user=user)
        return Response({'token': token.key}, status.HTTP_201_CREATED)

i dont understand why i have error

like image 794
Проолтпаа Прссмтлг Avatar asked Dec 05 '25 03:12

Проолтпаа Прссмтлг


1 Answers

You need to pass request.data, not just request, into the serializer.

serializer = self.serializer_class(data=request.data)
like image 53
Daniel Roseman Avatar answered Dec 07 '25 18:12

Daniel Roseman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!