1

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?

2
  • self.request.GET("user_id") or self.kwargs("user_id") ? Commented Oct 1, 2020 at 9:49
  • Are these different? Commented Oct 1, 2020 at 9:58

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0
...users/8/feed?category='x'

there is why i am also not getting category in post request

 category = request.GET.get('category')

because i have mantioned action in my form

<form method="POST" action="{url 'something'}"> ... </form>

so solution is that just remove action from form

<form method="POST" > ... </form>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.