简体   繁体   中英

How to add optional parameters in a django view keeping the same url

Let's say I have the following URL:

http://127.0.0.1:8000/en/project_page/1/

and my urls.py :

path(
    'project_page/<int:pid>/', 
    views.project_page,
    kwargs={'approvalid': None},
    name='project_page'
),

Generally speaking, the users will always access via http://127.0.0.1:8000/en/project_page/1/ , but in some cases I want to pass an optional parameter so that the page renders optional content.

For example, if the user access: http://127.0.0.1:8000/en/project_page/1/somevalue

I would like to see the content of somevalue in my view, like:

def project_page(request, pid, somevalue):
    if somevalue:
        #do something here with the optional parameter
    else:
        #run the view normally
    return render(request, 'mypage.html', context)

Once we get the optional parameter, I want the url structure to be the original:

http://127.0.0.1:8000/en/project_page/1/somevalue -> get the value of the optional parameter and get back to the original url -> http://127.0.0.1:8000/en/project_page/1/

What I've tried:

I thought kwargs would do the trick, but I did something wrong.

I found this from the official docs ( Passing extra options to view functions ) but it seems that I'm doing something wrong.

EDIT:

def project_page(request, pid, somevalue):
    context = {}
    context['pid'] = 'pid'
    if approvalid:
        context['nbar'] = 'example1'
        #some logic here
    else:
        context['nbar'] = 'example2'
        #some logic here
    return render(request, 'mypage.html', context)

If you choose to use query parameters, you could use Django's sessions to save somevalue , redirect to the same url but without the query parameters, then build the context based on that.

Something like this (not tested):

def project_page(request, pid):
    context = {}
    some_value = request.GET.get('somevalue')

    if some_value:
        # if somevalue is present in the query parameters, 
        # save it to the session and redirect
        request.session["approval_id"] = some_value
        return redirect('project_page')

    if request.session.get("approval_id"):
        context['nbar'] = "example1"
    else:
        context['nbar'] = "example2"

    return render(request, "mypage.html", context)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM