Home > Back-end >  Is it possible to pass a value from HTML page to Django view using GET method?
Is it possible to pass a value from HTML page to Django view using GET method?

Time:02-05

I have a base sidebar that contains two items page1 and page2. When the user clicks on an item, it will render the corresponding page. I also have a filter in the sidebar that allows the user to filter the results on the page by type. I am able to see to appropriate results on the page when I choose a filter, but my aim is to make the system remember the last filter selection so when the user chooses a new page, it will automatically show the results by the last selected filter. can this be done by sending the variable 'type' through the GET method? or any other solution would be appreciated.

in base.html, Rendering a New Page via Get method

<div id="page"  aria-labelledby="headingUtilities"
data-parent="#accordionSidebar">
    <div >
        <a  href="page1">Page1</a>
        <a  href="page2">Page2</a>
    </div>
</div>

in base.html, Filtering the current page via POST method

<div id="collapseTwo"  aria-labelledby="headingTwo" data-parent="#accordionSidebar">
    <div >
        <h6 >Filter By Type:</h6>
        <form name="modality" action="" id='type' method="post" enctype="multipart/form-data">
            {% csrf_token %}
            <input  name ='type' type="submit" value="type1" onclick="this.form.submit()">
            <input  name ='type' type="submit" value="type2" onclick="this.form.submit()">
            <input  name ='type' type="submit" value="type3" onclick="this.form.submit()">
        </form>
    </div>
</div>

django view:

@login_required(login_url='login')
def page1(request):
if request.method == 'POST':
    type = request.POST['type']
else:
    type = 'type1'


return render(request, "dashboard/page1.html",
                  {
                  'type': type,}

@login_required(login_url='login')
def page2(request):
if request.method == 'POST':
    type = request.POST['type']
else:
    type = 'type1'


return render(request, "dashboard/page2.html",
                  {
                  'type': type,}

Page1 HTML:

{% extends 'dashboard/base.html' %}

{% block content %}

    <h1> Page1: {{type}} </h1>

{% end block %}

Page2 HTML:

{% extends 'dashboard/base.html' %}

{% block content %}

    <h1> Page2: {{type}} </h1>

{% end block %}

CodePudding user response:

You can pass parametrs to get as follows

urlpatterns = [
  path('dashboard/page1/<type>, page1view),
  path('dashboard/page2/<type>, page2view)
]

and then use them

def page1view(request, type):
    pass

But I think you should use sessions instead. User will automatically send you his session identificator with each new request and django will get you all data, that you choose to store in that user session. Can be used as a dictionary.

request.session['type'] = type
type = request.session['type']
  •  Tags:  
  • Related