Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the value from the drop down box django?

Should I use the next construction?

def PageObjects(request): 
    q = bla_bla_bla(bla_bla) 
    answer = request.POST['value'] 


<form action="PageObjects" method="get">
       <select >
        <option selected="selected" disabled>Objects on page:</option>
        <option value="10">10</option>
        <option value="20">20</option>
        <option value="30">30</option>
        <option value="40">40</option>
        <option value="50">50</option>
       </select>
       <input type="submit" value="Select">
  </form>

How can I solve this problem? What do I need to write?

like image 883
Max L Avatar asked Jul 20 '12 19:07

Max L


People also ask

How do you receive data from a Django form with a post request?

Using Form in a View In Django, the request object passed as parameter to your view has an attribute called "method" where the type of the request is set, and all data passed via POST can be accessed via the request. POST dictionary. The view will display the result of the login form posted through the loggedin.

How do you get a value using a flask from a selected option in a drop down list?

to use select = request. form. get('comp_select') in the test view to get the value of the select element with the name attribute set to comp_select . to add a form with the select element with the name attribute set to comp_select .


2 Answers

give a name to tag, like

<select name="dropdown">
    <option selected="selected" disabled>Objects on page:</option>
            <option value="10">10</option>
            <option value="20">20</option>
            <option value="30">30</option>
            <option value="40">40</option>
            <option value="50">50</option>
    </select>

Access it in view like

def PageObjects(request): 
    q = bla_bla_bla(bla_bla) 
    answer = request.GET['dropdown'] 
like image 164
Paritosh Singh Avatar answered Oct 06 '22 19:10

Paritosh Singh


I would recommend sending your data with post:

<form action="PageObjects" method="post">
  <select >
    <option selected="selected" disabled>Objects on page:</option>
    <option value="10">10</option>
    <option value="20">20</option>
    <option value="30">30</option>
    <option value="40">40</option>
    <option value="50">50</option>
  </select>
  <input type="submit" value="Select">
</form>

And you should access your form values through the cleaned_data dictionary:

def page_objects(request):
  if request.method == 'POST':
    form = YourForm(request.POST)

    if form.is_valid():
      answer = form.cleaned_data['value']

I really recommend that you read the Django docs:

https://docs.djangoproject.com/en/1.4/topics/forms/#using-a-form-in-a-view

like image 35
Jens Avatar answered Oct 06 '22 17:10

Jens