简体   繁体   English

如何在保持相同 url 的 django 视图中添加可选参数

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

Let's say I have the following URL:假设我有以下 URL:

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

and my urls.py :和我的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.一般来说,用户总是通过http://127.0.0.1:8000/en/project_page/1/访问,但在某些情况下我想传递一个可选参数,以便页面呈现可选内容。

For example, if the user access: http://127.0.0.1:8000/en/project_page/1/somevalue例如,如果用户访问: http://127.0.0.1:8000/en/project_page/1/somevalue

I would like to see the content of somevalue in my view, like:我想在我看来看到somevalue的内容,例如:

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:一旦我们得到可选参数,我希望 url 结构是原来的:

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/ http://127.0.0.1:8000/en/project_page/1/somevalue -> 获取可选参数的值,回到原来的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.我以为kwargs会成功,但我做错了什么。

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.如果您选择使用查询参数,您可以使用 Django 的sessions来保存somevalue ,重定向到相同的 url 但没有查询参数,然后基于它构建上下文。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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