I am building and Inventory Web App and I am facing this error. I am trying to get Username from token to show a custom hello message and show that the user is logged in as someone.
Here is my Views.py that gets Token from localStorage as logged in user:
class UserDetails(APIView):
def post(self, request):
serializer = UserAccountTokenSendSerializer(data=request.data)
global token
if serializer.is_valid():
token = serializer.validated_data['token']
return Response(serializer.data)
def get(self):
user_id = Token.objects.get(key=token).user_id
details = User.objects.get(id=user_id)
serializer = UserDetails(details, many=False)
return Response(serializer.data)
class UserDetails(serializers.ModelSerializer):
class Meta:
model = User
fields = (
'username',
)
Here is my Urls.py:
urlpatterns = [
path('get-user-token/', views.UserDetails.as_view()),
path('get-user-details/', views.UserDetails.as_view()),
]
And this is the error that I get:
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
TypeError: get() takes 1 positional argument but 2 were given
[15/Jun/2022 19:34:59] "GET /api/v1/get-user-details/ HTTP/1.1" 500 82239
CodePudding user response:
The .get(…)
method [Django-doc] takes a request
parameter as well, even if you do not use it, so:
class UserDetails(APIView):
# …
def get(self, request):
# …
pass
I would strongly advise, not to make token
a global variable. The same webserver can be used for another user that thus has not authenticated (properly). Take a look at the Authentication section of the Django REST framework documentation for more information on how to authenticate and check credentials.
Note: In Django, class-based views (CBV) often have a
…View
suffix, to avoid a clash with the model names. Therefore you might consider renaming the view class toUserDetailsView
, instead of.UserDetails