user1581390
user1581390

Reputation: 2018

Django: passing parameters not inside the URL

Right now I have a very long URL for my results which is basically a long list of parameters. I navigate to the results by press of a button and (JavaScript):

window.location.href = ... URL with parameters here ...;

Catching them like this (views.py):

def Results(request,parameter1,...,parameterN)

How do I send these same parameters not inside the URL and how do I catch them in views?

EDIT:

To clarify, in a an optimal world I'd like to send the parameters hidden from the user and search engine crawlers so that the user/crawler sees only the URL:

www.example.com/results

And I do something like:

def Results(request):
    parameter1 = ???
    parameter2 = ???
    ...
    parameterN = ???

Upvotes: 0

Views: 5766

Answers (2)

Mehran Torki
Mehran Torki

Reputation: 987

When you need to hide parameters, you should send POST request. To send parameters using POST method, you can send them using html form element or javascript. For example you can pass parameters with form like this :

<form id="my_form" action="/results" method="POST">
    {% csrf_token %}
    <input type="hidden" name="param1" value=""/>
    <input type="hidden" name="param2" value=""/>
    <input type="hidden" name="param3" value=""/>
</form>

Populate hidden input elements in javascript like this:

var my_form = document.forms['my_form'];
my_form.elements["param1"].value = "Some Value1";
my_form.elements["param2"].value = "Some Value2";
my_form.elements["param3"].value = "Some Value3";

And to submit the form in javascript :

document.getElementById("my_form").submit();

Then access parameters in view :

def Results(request):
    if request.method == "POST":
        parameter1 = request.POST.get("param1", None)
        parameter2 = request.POST.get("param2", None)
        parameter3 = request.POST.get("param3", None)
    else:
        # handle get request

Read here if you want to send POST request using javascript: Sending an HTTP Post using Javascript triggered event

Upvotes: 5

Aviah Laor
Aviah Laor

Reputation: 3658

You access the url parameters in the GET dictionary

www.example.com/?parm1=baz&&parm2=baz

In the view:

def ViewFunction(request):   
   parm1 = request.GET['parm1']
   parm2 = request.GET['parm2']

If these parameters are optional, you will want to use a default, like:

parm1 = request.GET.get('parm1',None)

Note that the GET parameters are not safe. You should escape them properly before using them in the code. An easy solution is to use a django form, pass the GET values to the form, and then use the form.cleaned_data.

When you have too many parameters, check your view and urls, maybe you can convert some parameters to a url captured args.

Upvotes: 2

Related Questions