I’m implementing JWT authentication in my Django project and at the moment I’m stuck in a part where I’d like to filter response data by my JWT.
I’d like to get particular data referring to authenticated user in my Django view. How can I get this filtered data?
Here’s example for my Settings view.
Views.py
Class SettingsViewSet(viewsets.ModelViewSet):
# here I'd like to decode my JWT token
# and filter the response data for particular user
queryset = Settings.objects.all()
serializer_class = SettingsSerializer
urls.py
# ...
router.register(r'api/settings', SettingsViewSet)
# ...
urlpatterns = [
# ...
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url('api/token/', jwt_views.TokenObtainPairView.as_view(), name='token_obtain_pair'),
# ...
]
Serializers.py
class SettingsSerializer(serializers.ModelSerializer):
class Meta:
model = Settings
fields = ('id', 'name', 'value', 'description', 'office')
settings.py
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_simplejwt.authentication.JWTAuthentication',
],
}
Here’s a curl command which I use to get response from server:
curl -H ‘Content-Type: application/json’ http://127.0.0.1:8000/api/settings/ -H ‘Authorization: Bearer <Here goes JWT token for particular user>’
In response I get all the settings for all users. I’d like to get data only for the authenticated one.
Currently logged in user instance should be automatically added to request objects by the library you are using. With that, you can override get_queryset method to filter the response by currently logged in user, assuming you have a user field in your Settings model:
class SettingsViewSet(viewsets.ModelViewSet):
queryset = Settings.objects.all()
serializer_class = SettingsSerializer
def get_queryset(self):
queryset = Settings.objects.filter(user=self.request.user)
return queryset