Hello I am trying to use the .GET form method on a check box, select tag and radio button in Python2.7 utilising google app engine and thats it.
here is the code so far
HTML
<form method='GET'>
<input type="checkbox" name="name" value="checkbox">
<select name='select'>
</form>
Python Code
select = self.request.GET['select']
checkbox = self.request.GET['name']
This works for my standard input fields (such as text) but not on any other type of input I use. I have looked everywhere for the documentation on this but have come up empty, any help would be appreciated.
Thanks in advance!
When a checkbox is not checked, the browser doesn't send the field.
GET is a MultiDict object, which acts just like a dictionary. As such you can use containment testing with in to see if the checkbox is present in the request:
checkbox = 'name' in self.request.GET
This sets a boolean True or False.
Alternatively, test for it instead with the .get() method:
checkbox = bool(self.request.GET.get('name'))
GET.get('name') returns None (a false value) if the checkbox is missing from the request, otherwise it'll return 'checkbox' (a true value).
For <select> elements, if none of the options are selected, it too is omitted from the request. If there is a default value you'd pick, then you can do so with:
select = self.request.GET.get('select', 'default value')
For the precise rules as to what a browser will include in the form, see the Successful controls specification; only controls that are successful are included.
Related
I have a Flask site that has a 'search bar' where you type in the location ID of a particular location and then click Submit to be taken to the page for that location, if it exists. Here's the current form action:
<form id="locationinfo" action="{{ url_for('location') }}">
When you click Submit you are taken to /location?info=SITEID and that works just fine. What I want to do is change this behavior slightly so that when a user clicks Submit they are taken to /location/SITEID/ instead. I have the decorator set up in my main Flask routes file, but I'm struggling to put the pieces together to get this simple form together.
#app.route("/location/<locationid>/")
def locations(locationid):
...
return locationid
Any direction would be greatly appreciated!
[Edit with current full form code]
#app.route("/location")
def location():
location_id = request.args.get("info")
<form id="info" action="{{ url_for('location') }}">
<input type="text" name="info" id="locationfield">
<button type="submit">Go!</button>
</form>
You can't change how HTML forms submit their fields, they will always be in the query string or body (POST). One option is to use JavaScript to override the submit event to perform your own submit and re-render with the results.
A simpler solution is to redirect to the nice url after submit. This keeps the "search" action separate from the "show" action (even if they are handled by the same view).
#app.route('/location/')
#app.route('/location/<int:id>/')
def location(id=None):
# redirect to the second form if the id wasn't in the path
# raises 400 error if id wasn't in the query
if id is None:
return redirect(url_for('location', id=request.args['info']))
# id is in the path, continue
...
You can expand this later if you want to search by something besides id. Perform the search then redirect to the found id.
In the process of teaching myself how to use python's tornado web framework, I am trying to create a simple web server and some web pages. On one of the web pages, I have two buttons: one to log users out and redirect them back to the login page and one to submit a blog post. They are both "post" requests and have their name values in html set to "logout" and "new_post".
My questions is, how can I tell which button was pressed so that the post() method for the page's RequestHandler can perform the correct actions in each case? Is there a way to grab the "name" of the button pressed?
When you submit a form with a button click, a parameter with the name of the clicked button gets added to the request.
You can check, if the parameter exists and then do your stuff.
def post(self):
if self.get_argument("logout", None) != None:
# do logout stuff
if self.get_argument("new_post", None) != None:
# do submit a blog post stuff
On Python3 using Tornado, the setup looks as follows with two submit buttons (which is very similar to the above answer).
First the HTML and note both buttons are similar with differing display values. The name parameter is what will be passed to Tornado's POST handler:
<p><input type="submit" class="button" name="basic" value="Basic Query"></p>
<p><input type="submit" class="button" name="advanced" value="Advanced Query"></p>
Next, the POST handler. Using get_argument, you can specify the name and select it if the input is not null. Remember to include the ", None" in get_argument so that it defaults to None should the option not be selected:
def post(self):
if self.get_argument('basic', None) is not None:
self.write('Basic Query')
elif self.get_argument('advanced', None) is not None:
self.write('Advanced Query')
That's it! 2 forms and the ability to differentiate between. Happy coding!
In django I do the following to get the value of an text box for example:
On my HTML page:
<input type="text" name="inputBox" id="inputBox" />
ON the views.py page:
valueOfTextBox= request.POST.get('inputBox', False)
How do I get whether a ceck box is 'checked' or not??
<input type="checkbox" id="selectAll">
If the inputBox is included in request.POST it has been checked. Therefore you could do the following.
if request.POST.get('selectAll', False):
...do stuff...
See this answer for details.
It's exactly the same, just write:
request.POST.get('selectAll', False)
You don't have value="" attribute on you checkbox so in case it is checked, your POST variable will have value 'on', if not checked, the variable will not be in your POST dict. So you can check it like described in previous answers.
PS: You don't need to write False as the second parameter to get() method, it will automatically return None what is in boolean the same as False.
I've seen a couple of documents on how to collect the data from a HTML statement in Django but none of them were very clear to me. Does anybody have a real working example to share?
In my case I have something like this in my template file:
<select title="my_options">
<option value="1">Select value 1</option>
<option value="2">Select value 2</option>
</select>
What goes in the views.py in order to collect the selected value? Thank you!
If it's a GET request, request.GET['my_options']. If it's a POST, then request.POST['my_options']. This will be a string, either "1" or "2" (or "<script>alert('I hacked you!')</script>")
Either way, it's probably better to use the Django forms framework to save you the hassle of writing the HTML, and sanitizing the returned values.
Manage data via POST
def yourView(request):
# Use '.get('id', None)' in case you don't receive it, avoid getting error
selected_option = request.POST.get('my_options', None)
if selected_option:
# Do what you need with the variable
One thing that may be useful with forms in Django is to make different things if you make a POST to the URL or just load it:
def yourView(request):
if request.POST: # If this is true, the view received POST
selected_option = request.POST.get('my_options', None)
if selected_option:
# Do what you need to do with the variables
return render_to_response(...)
return render_to_response(...)
There are 2 render_to_response in case you need to do different things if the view was just loaded or receive a POST.
Manage data via GET
def yourView(request):
# Use '.get('id', None)' in case you don't receive it, avoid getting error
selected_option = request.GET.get('my_options', None)
if selected_option:
# Do what you need with the variable
Background:
Using urllib and urllib2 in Python, you can do a form submission.
You first create a dictionary.
formdictionary = { 'search' : 'stackoverflow' }
Then you use urlencode method of urllib to transform this dictionary.
params = urllib.urlencode(formdictionary)
You can now make a url request with urllib2 and pass the variable params as a secondary parameter with the first parameter being the url.
open = urllib2.urlopen('www.searchpage.com', params)
From my understanding, urlencode automatically encodes the dictionary in html and adds the input tag. It takes the key to be the name attribute. It takes value in the dictionary to be the value of the name attribute. Urllib2 send this html code via an HTTP POST request.
Problem:
This is alright if the html code you are submitting to is formatted in a standard way with the html tag input having the name attribute.
<input id="32324" type="text" name="search" >
But, there is the situation where the html code is not properly formatted. And the html input tag only has an id attribute no name attribute. Is there may be another way to access the input tag via the id attribute? Or is there may be yet another way?
Solution:
?
According to the W3 standard, for an input field to be submitted, it must have a name attribute. A quick test on Firefox 3 and Safari 3.2 shows that an input field that is missing the name attribute but has an id attribute is not submitted.
With that said, if you have a form that you want to submit, and some of its fields have id but not name attributes, using the id attribute instead seems like the only available option. It could be that other browsers use the id attribute, or perhaps there is some JavaScript code that handles the submission event instead of letting the browser do it.
An input tag without a name won't be submitted as a form parameter.
For example, create an HTML page containing just this:
<form>
<input type="text" name="one" value="foo"/>
<input type="text" value="bar"/>
<input type="submit"/>
</form>
You can see that the second text field is missing a name attribute. If you click "Submit," the page will refresh with the query string:
test.html?one=foo
A good strategy for this would be to look at a live POST request sent by your browser and start by emulating that. Use a tool like the FireBug extension for Firefox to see the POST request and parameters sent by your browser. There might be parameters in there that you didn't notice before -- possibly because they were hidden form elements or they were created/set by JavaScript.