Python Requests library to fill out option list

Viewed 1596

I'm trying to fill out a web form using python requests. Does anyone know the correct syntax when there is a drop down (option list)?

I can successfully post to the text boxes on the form, but not the option list

import requests

URL = 'http://127.0.0.1:8000/recoater/new/'
payload = {
   'data': '40',
   'machine': '"1">MachineA<',
}

r = requests.post(URL, data=payload)
print (r)
print(r.text)

Returns this:

<ul class="errorlist"><li>Select a valid choice. That choice is not one of 
the available choices.</li></ul>
<p><label for="id_machine">Machine:</label> <select name="machine" required 
id="id_machine">
<option value="">---------</option>
<option value="1">MachineA</option>
1 Answers

For a <select>..</select>, the POST data sends the value=".." of the selected <option>, so in case you want MachineA, you should send it with 'machine': '1', as payload:

import requests

URL = 'http://127.0.0.1:8000/recoater/new/'
payload = {
   'data': '40',
   'machine': '1',
}

r = requests.post(URL, data=payload)
print (r)
print(r.text)

The Django forms (or other mechanisms that handle the request) have logic in place to map this value back to the machine that is associated with this value: after all, the text in the option is just a textual representation of the Machine object, it can contain a lot of (extra) data that is not displayed (or is displayed, but in a non-structured way).

So a browser will for a webpage:

<select name="machine" required id="id_machine">
    <option value="">---------</option>
    <option value="1">MachineA</option>
</select>

Send in the POST data an entry that associates the name of the <select> (here 'machine') that is associated with the value of the option picked (here '' or '1'). Just like a <input name="data" type="text"> has a value parameter as well that is set to the value you enter in the textfield.

Related