Search code examples
djangodjango-urlsurl-parameters

django add url parameter in a view function


I am building a follower list view, frontrend allows user to search followers on a specific user by request.GET

After adding the pk on the url in frontend, we use something like /?user=2 To find all followers of user 2.

Here’s the issue. The frontend must have user parameter to indicate who you searching, show a user card in the search box. And the backend, if there is no user Param set, will target followers of request.user.

When the url is /, I am actually going for /?user=request.user.pk, can I add this parameter in view function? Or how can I re-parse the url and call the view function again when default?

Something to add manipulate param before redirect

def userFollowerView(request):
    user = request.GET.get('user', None)
    if not user:
        request.path.setParam('user', request.user.pk)
        return userFollowerView(request) # or redirection
    return ...

The reason I am not using a regex pattern to indicate user Pk and another url for redirection, is that, this is a minimised example, in real life I am dealing with a pk list on other scenario that must be passed as url param.


Solution

  • You can do it using redirect() with the help of f-string like this:

    def userFollowerView(request):
        user = request.GET.get('user', None)
        if not user:
            return redirect(f'/<your_url>/?user={request.user.id}')
        # Below this have your URL's default code
    

    This would work as you intend it to be, the URL will load with the requested user's id


    Solved by

    def userFollowedView(request):
        try:
            # support list param: &tag=2&tag=3 => [2, 3]
            users = list(map(lambda x:int(x), dict(request.GET)['user']))
            profiles = Profile.objects.filter(user__prof_followed_set__in=users)
        except KeyError:
            p = request.build_absolute_uri()
            if '?' in p:
                p += f'&user={request.user.pk}'
            else:
                p += f'?user={request.user.pk}'
            return redirect(p)