'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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
