aniket
aniket

Reputation: 95

Getting all request input values

I am new to django so it could be a very basic problem.
In my django template form, I have put a lot of input fields to fill
like this

<form method="POST">
        <input type="text" name="n_1" value="" />
        <input type="text" name="n_2" value="" />
        <input type="text" name="n_3" value="" />
        .
        .
        .
        <input type="text" name="n_ " value="" />
    <input type="submit"  value="submit" />
</form>

To access all inputs,I can do it one by one like asking request.POST["n_i"] by varying i in loop.
I am looking to find a way by which I can get all the values in a list or in string and I don't have to look by name of input field.

Upvotes: 2

Views: 8592

Answers (3)

Vivek Sable
Vivek Sable

Reputation: 10223

Get form values into Django View:

Get values from the Request - request.POST.values()

Get keys(input name) from the Request- request.POST.keys()


Get all keys and values from the request in dictionary:

zip(request.POST.keys(), request.POST.values())

Upvotes: 3

catavaran
catavaran

Reputation: 45575

You can iterate through the whole request.POST and get the values of the text fields:

values = [value for name, value in request.POST.iteritems()
                if name.startswith('n_')]

startswith() is required to filter out the submit value of the button.

But imho the better option is to use the inputs with the same name and get the values with the getlist() method:

<form method="POST">
        <input type="text" name="n" value="" />
        <input type="text" name="n" value="" />
        <input type="text" name="n" value="" />
        .
        .
        .
        <input type="text" name="n" value="" />
    <input type="submit"  value="submit" />
</form>

And the in the view:

values = request.POST.getlist('n')

Upvotes: 2

Wtower
Wtower

Reputation: 19912

As @Vivek Sable mentioned in his comment, you can use request.POST.values() and request.POST.keys(). Another possibility is to convert the POST dictionary into a list of tuples with request.POST.items().

Apart from those, I would strongly recommend you to consider using a standard Django Form class:

forms.py:

from django import forms

class NameForm(forms.Form):
    your_name = forms.CharField(label='Your name', max_length=100)

template:

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

Then you would be able to construct the form from the post data as such:

form = NameForm(request.POST)

And after calling form.is_valid() he collected data will be in form.cleaned_data.

More on forms on Django documentation: Working with forms.

Upvotes: 1

Related Questions