How to get value from django dropdown?

Should I use the following construct?

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?

+5
source share
3 answers

I would recommend sending your details in a message:

<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 a dictionary cleaned_data:

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

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

I really recommend you read the Django docs:

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

+3
source

enter a tag name e.g.

<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 to it as

def PageObjects(request): 
    q = bla_bla_bla(bla_bla) 
    answer = request.GET['dropdown'] 
+6
source

forms.py 'your_app_folder'

forms.py:

class FilterForm(forms.Form):
    FILTER_CHOICES = (
        ('time', 'Time'),
        ('timesince', 'Time Since'),
        ('timeuntil', 'Time Untill'),
    )

    filter_by = forms.ChoiceField(choices = FILTER_CHOICES)

views.py

from .forms import FilterForm

def name_of_the_page(request):
 form = FilterForm(request.POST or None)
 answer = ''
 if form.is_valid():
  answer = form.cleaned_data.get('filter_by') 
  // notice `filter_by` matches the name of the variable we designated
  // in forms.py

html:

<tr><th><label for="id_filter_by">Filter by:</label></th><td><select id="id_filter_by" name="filter_by" required>
<option value="time" selected="selected">Time</option>
<option value="timesince">Time Since</option>
<option value="timeuntil">Time Untill</option>
</select></td></tr>

Pay attention to the parameter field with the selected attribute when submitting the form to the views.py file, you will capture data from the attribute selectedusing the line

answer = form.cleaned_data.get('filter_by')
0
source

All Articles