Mayank Agrawal
Mayank Agrawal

Reputation: 11

Django request.GET('variable') for multiple values

I have an HTML file which returns multiple GET values to my django view.py file.

If I submit only one value to view.py and read it with:

request.GET('variable')

then it works fine. But I am not sure how to GET multiple values.

I tried:

request.GET.getlist('variable1')
request.GET.getlist('variable2')

but it doesn't work.

My HTML file is:

<form action="/hello/" method="GET">
First_Name:<input type="text" name="arr[0]"><br>
Last_Name:<input type="text" name="arr[1]"><br>
<input type = "submit" value = "Submit">
</form>

My view.py file in the django app is:

def hello(request):
  fn=request.GET['arr[0]']
  ln=request.GET['arr[1]')
  print fn
  print ln

I have also tried:

fn=request.Get.getlist['arr[0]']
ln=request.Get.getlist['arr[1]']

What am I doing wrong?

Upvotes: 1

Views: 1977

Answers (2)

Daniel Roseman
Daniel Roseman

Reputation: 599866

Drop the square brackets and indexes. Those are from PHP or Rails and have no place in Django.

Upvotes: 1

Deja Vu
Deja Vu

Reputation: 731

Check this out.

For example,

# views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect

from .forms import NameForm

def get_name(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = NameForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            # ...
            # redirect to a new URL:
            return HttpResponseRedirect('/thanks/')

    # if a GET (or any other method) we'll create a blank form
    else:
        form = NameForm()

    return render(request, 'name.html', {'form': form})

and

# html
<form action="/your-name/" method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit" />
</form>

Upvotes: 0

Related Questions