I am trying to access the category
key from the following url within my view:
...users/8/feed?category='x'
However, when I run self.kwargs
within my view, it only returns 'user_id': 8
.
File urls.py
:
path('users/<int:user_id>/feed', views.Posts.as_view())
File views.py
:
class Posts(APIView):
def get(self, request, **kwargs):
return Response(self.kwargs)
What would I change such that self.kwargs
returns "user_id": 8, "category": 'x'
rather than just "user_id": 8
?
It is important that this stays as a query string parameter using '?'. Additionally, I've seen other people implementing similar things using self.request.GET
, what is the difference between using this and self.kwargs
?
In a Django view, self.kwargs
holds the URL parameters (the parts that are specified in the URL conf, like <int:user_id>
in your code) and self.request.GET
holds the query string parameters (the parts after the ?
)
To get data from both:
class Posts(APIView):
def get(self, request, **kwargs):
print(self.kwargs['user_id'])
# this returns None if there was no category specified
print(self.request.GET.get('category'))
new_d = {
'user_id': self.kwargs['user_id'],
'category': self.request.GET.get('category'),
}
return Response(new_d)