9
9
95506682021-01-11 22:52:55
Django
9550668, 2021-01-11 22:52:55

How to get a variable from a GET query string?

Hello. I send a GET request with a string like:
127.0.0.1:8000/api/users/23/profile
It is written in the url

path(
        "<int:user_id>/profile/",
        ProfileUpdate.as_view(),
        name="profile-api-update",
    ),

How can I get user_id in view (function def get_queryset(self))? (via self.request or something else)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
WStanley, 2021-01-12
@WStanley

There is midlleware in django. django.contrib.auth.middlewareIt just puts an authorized user in request, so in all views in request you can access and get an authorized user like this:

def get_queryset(self)
    user = self.request.user # тут юзер
    user_id = self.request.user.id # так ИД юзера

https ://docs.djangoproject.com/en/3.1/ref/middlewa... And it makes no sense to
pass the ID of an authorized user via url /http/...
path("<int:my_param>/profile/", ProfileUpdate.as_view(), name="profile-api-update" ),
# Только я бы последним параметр передавал, вот так
# path("/profile/<int:my_param>/", ProfileUpdate.as_view(), name="profile-api-update" ),

class ProfileUpdate(View):

    def get(self, request, my_param):
        print(my_param)
        return render(request, self.template_name)

    def post(self, request, my_param):
        print(my_param)
        return render(request, self.template_name)

    def get_queryset(self):
        my_param=self.kwargs['my_param']
        my_param=self.kwargs.get('my_param') # лучше так

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question