models.py
class Customer(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
mobile = models.PositiveBigIntegerField(unique=True)
def __str__(self) -> str:
return self.user.username
serializers.py
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['id', 'first_name', 'last_name', 'username', 'email']
def __init__(self, *args, **kwargs):
super(UserSerializer, self).__init__(*args, **kwargs)
self.Meta.depth = 1
authentication.py
class JWTAuthentication(BaseAuthentication):
def authenticate(self, request):
print('authenticating')
auth = get_authorization_header(request).split()
print(auth)
if auth and len(auth) == 2:
token = auth[1].decode('utf-8')
print('Decoded Token')
print(token)
id = decode_access_token(token)
print(id)
print(id)
customer = models.Customer.objects.get(id=id)
return (customer, None)
raise exceptions.AuthenticationFailed('unauthenticated2')
def decode_access_token(token):
try:
payload = jwt.decode(token, 'access_secret', algorithms='HS256')
print('accesstoken')
print(payload)
return payload['customer_id']
except Exception as error :
print('For token %s error detected %s', token, error)
raise exceptions.AuthenticationFailed('unauthenticated1 ', error)
def create_access_token(id):
print('AccessTokentime : ', current_time)
print('access_token_expiry : ', access_token_expiry)
return jwt.encode({
'customer_id': id,
'exp': access_token_expiry,
'iat': current_time,
}, 'access_secret', algorithm='HS256')
urls.py
path('user/', UserDetails.as_view()),
views.py
class UserDetails(generics.RetrieveUpdateDestroyAPIView):
queryset = models.User.objects.all()
serializer_class = serializers.UserSerializer
authentication_classes = [ JWTAuthentication ]
def get_queryset(self):
qs = super().get_queryset()
print('self.request.user.id ', self.request.user.id)
customerObj = models.Customer.objects.get(id=self.request.user.id)
print('customerObj ', customerObj.user.id)
return qs.get(id=customerObj.user.id)
I am using Postman to make a request to URL http://127.0.0.1:8000/api/user/ with header containing 'Authorization' key and 'Bearer ' value. As seen in the view.py snippet, I see logs as self.request.user.id 2 customerObj 4.
Stacktrace:
Internal Server Error: /api/user/ Traceback (most recent call last): File "/opt/homebrew/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/opt/homebrew/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/opt/homebrew/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 56, in wrapper_view return view_func(*args, **kwargs) File "/opt/homebrew/lib/python3.10/site-packages/django/views/generic/base.py", line 104, in view return self.dispatch(request, *args, **kwargs) File "/opt/homebrew/lib/python3.10/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/opt/homebrew/lib/python3.10/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/opt/homebrew/lib/python3.10/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/opt/homebrew/lib/python3.10/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/opt/homebrew/lib/python3.10/site-packages/rest_framework/generics.py", line 282, in get return self.retrieve(request, *args, **kwargs) File "/opt/homebrew/lib/python3.10/site-packages/rest_framework/mixins.py", line 54, in retrieve instance = self.get_object() File "/opt/homebrew/lib/python3.10/site-packages/rest_framework/generics.py", line 88, in get_object assert lookup_url_kwarg in self.kwargs, ( AssertionError: Expected view UserDetails to be called with a URL keyword argument named "pk". Fix your URL conf, or set the
.lookup_field
attribute on the view correctly. [30/Nov/2023 17:27:17] "GET /api/user/ HTTP/1.1" 500 97185