Flask: buttons with varying functions - html

I'm writing a program in flask. In one of the pages (/search), the user will have a field to enter a string and click a search button. The result page that follows works all right, which consists of an html page with several images on it.
Now i want to add a button next to each image that, once clicked, will add an item to my mongoDB database.
So, 2 problems:
1) The buttons i managed to create so far will demand a "return redirect(page)". I don't want that. The user must be allowed to click several buttons in sequence, instead of having to perform a new search.
2) i built my own mechanism for rendering the result.html page. According to the search results, my code opens result.html and writes (appends) the urls on it.
#app.route('/add', methods = ['POST'])
def add():
print "hi"
return None ##Python won't accept 'return None' here =(
[...]
w=open("result.html", "a")
[...]
for k in cursor:
try:
w.write(k['url'] + "'> <form action='/add' method='post'> \
<input type='submit' value='Add'></input></form>")
How can i make the button tell the /add view function know the url for each image? I suppose there is something i should replace in this last block of code.

Related

Django Admin: How to use the button to move to the selected URL?

I am very new to Django and trying to make my first project. I find it difficult to use the buttons I created to move to the selected URL.
Let's say my app is called TestForms and my models are: Patients, General, PST and ERBT. I would like to create two buttons - 'Previous' and 'Next' - which will be used to go to previous/next forms respectively. I try to do so using admin templates in django.
NOTE: I know changing built-in templates are not a very good idea, I will create new html file to extend this templates before doing changes on the server. For now I am doing it locally on my computer.
In submit_line.html I created two new buttons and they are like so:
{% if show_save_and_go_to_next_form %}<input type="submit" value="{% translate 'Next' %}" class="default" name="_gotonextform">{% endif %}
{% if show_save_and_go_to_previous_form %}<input type="submit" value="{% translate 'Previous' %}" class="default" name="_gotopreviousform">{% endif %}
This gives me two good-looking buttons on the site.
But these are just saving the results (working like 'Save' button), but not redirecting me to the next form as I would like to. When I am adding a new patient (admin/TestForms/patient/add/), after clicking on 'Next' I would like the server to save this patient and redirect me to admin/TestForms/general/add/ to be able to fullfil the next form, then save the changes and move on to admin/TestForms/PST/add/and so on.
I know I have to add the anchor, but I tried multiple times with different approaches and nothing worked. When I try to use <a href ...>, the button disappears. Also it is difficult for me to figure out how to move from one form to another and to disable the 'Previous' button on the first form and the 'Next' button on the last form.
Any suggestions how to achieve it?
The redirect needs to be done in your view, not in the template.
def your_view(request, *args, **kwargs):
# your code ...
if request.POST.get('_gotonextform'):
return redirect('admin/TestForms/general/add/')
else:
# do whatever you like if any other button was clicked
pass

How to get clicked img src and pass it to the next view function

I am using flask to deploy my model for image similarity search. To run it, I will have two pages:
1) first page (say, query.html) that shows a randomly generated image from my dataset; users can continue to refresh this page till they see an item that they like. In html, it would be something like <img src="{{ random_path }}" alt="">. When the user is satisfied, the image needs to be clicked to direct to the next page;
2) second page (say, results.html) that takes the img src from the first page, and run the model at backend and return the similar images.
I am now confused how I should link step 1) to step 2) - how to get the img src on click and pass that information on to the next step?
You can use a form with hidden input tags and make a post request (More on flask's post request here) to pass on the data from one page to the other. In code it would look something like this:
HTML:
<html>
<body>
<form action = "/imagematch" method = "post">
<p><input type = "hidden" name = "imagesrc" /></p>
<p><input type = "submit" value = "submit" /></p>
</form>
</body>
</html>
Python Backend:
#app.route('/imagematch',methods = ['GET', 'POST'])
def login():
if request.method == 'POST':
user = request.form.get('imagesrc')
Alternatively you can use JavaScript localstorage/sessionStorage. More on localstorage here:
Write a <form> and place the <input type="hidden"> (with base64 format of the image as value) or <input type="hidden"> (with the server file path as value) whichever comfortable and upon submitting the form the image path/base64 format of the image as value will be sent to server.
Or
Using Javascript or JQuery upon user selects the image, send the image to the server via a AJAX request and do whatever you want at the server-side and return the status to the user accordingly.
Option 1 is simple and straight forward and you need to deal with base64 conversion.
Option 2 is a little complex and needs good JQuery expertise.

Simple cross domain form posting not working (whmcs)

I am trying to get a search box to post its content into a searchbox on another domain, using the html post method, however its not working after being redirected to the second site the search box remains empty on site 2.
Both servers belong to the same business and I have access to both, can someone tell me what I could do without using java to get the contents from the input box 1 on site 1 posted to the input box 2 on site 2
here is the line of code I am using on the first site.
form action="https://site2.com/cart.php?a=add&domain" method="post"
Thanks
You''ll need to catch and process both the GET arguments (in your action URL) and the POST stream (from the form elements) in the site2.com/cart.php file that you are using as the action.
Assuming the input box on site1 is named inputBox and is contained in the form with that action, when the form is submitted the site2.com/cart.php script can access the value at $_POST['inputBox'] - ie, wherever that goes on site2, you could do
<form name="someformonsite2" action="....">
<input type=text
<?php
if((!empty($_POST['inputBox'])&&(passes_your_validation($_POST['inputBox']))){
print("value=\"".$_POST['inputBox']."" );
}
?>
size=12 maxlength=11>
<!-- rest of form follows -->
Which would effectively send to the browser:
<input type=text value="SomeVal" size=12 maxlength=11>

submitting form in auto it

The problem is :
I have form in html which contain :-
"two text-box" and " bottom to submit"
What I want is :
Make the script in automatically add some text and submit form without opening an internet explorer window (just the script).
I tried to implement a get and post, but it failed
#include<ie.au3>
$oHTTP = ObjCreate("winhttp.winhttprequest.5.1")
$oHTTP.Open("GET", "http://localhost/2.html", False)
_IELinkClickByText( $oHTTP , "submit")
$oHTTP.Send()
You can do it with WinHttp.au3 - https://www.autoitscript.com/forum/topic/84133-winhttp-functions/
Check on _WinHttpSimpleFormFill which fills a form and then submits
Functions with "_IE" prefix is not used for WinHttp object. So, you cannot call the _IELinkClickByText function.
Example using IE UDF to submit a form:
#include <IE.au3>
Local $oIE = _IECreate('http://localhost/2.html')
Local $oForm = _IEFormGetCollection($oIE, 0)
_IEFormSubmit($oForm)
But if you want to use WinHttp, you should use the POST method instead of GET.

HTML: Update page vs. Redirecting to a New Page After User Input

I'm trying to write some HTML code so that a table will be created on the current page after the user submits inputs into a form. That is, instead of entering in values into a form, clicking submit, and being redirected to a new page with the computed output values, I'd like for the output values to appear at the bottom of the current page. This way, the user inputs stay intact and the only change is that an output table is appended to the bottom of the current page. Here's an example of how I would ideally like the page to work:
http://amort.appspot.com/
Any help would be very much appreciated. Thanks!
You need your form action to point to same page. lets say the URL of your page is
http://example.com/page.php than you need to point your action to same page.
<form action='http://example.com/page.php'> and have inside your form a hidden field say
<input type='hidden' name='formSubmitted' value='1' > when this form is submitted to itself you can check if hidden field has a value through the get parameters.
Once you get that value you can make a condition check to show up a table. But ofcoursr you will need to use a server side language like jsp or php for that.
One alternate way is you do not submit your form. But instead have a javascript called when you click submit query button. This javascript will read the values from the filled in form boxes and will display them in the table below.
You can use PHP in your HTML file.
Example
simply create you form like so.
<form action="welcome.php" method="get">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
When the user clicks the "Submit" button, the URL sent to the server could look something like this:
http://www.w3schools.com/welcome.php?fname=Peter&age=37
The "welcome.php" file can now use the $_GET function to collect form data (the names of the form fields will automatically be the keys in the $_GET array):
Then create a table and add the lines are the right places. so this would be your table for example and what you would write in the HTML file its as simple as that.
Welcome <?php echo $_GET["fname"];?>.<br />
You are <?php echo $_GET["age"]; ?> years old!
Hope that helps.
Let me know if it does. Thanks
PK
You need to use javascript to do this. If you provided the current code of your page and the specific goal you wish to accomplish then I could give an example script, however if you feel comfortable coding it yourself then just look up javascript tutorials.
You could easily do this with jQuery. Submit the form to the calculator page with .ajax(), and have the calculator output its results as JSON. You can then output that result in the bottom table without the user ever leaving/reloading the page.
Hope this helps.
You don't say what you're using to process the form, but you won't be able to process it with just HTML. So you'll need some sort of processing with another language.
As others have mentioned, you could do this with JavaScript. AJAX would be one way, but you could write your own code to do this if you really want to (but I wouldn't recommend it if you don't have to).
Another way to do this is with PHP. Have the page process itself when the form is submitted.
Similar to the PHP suggestion, you could do this via a CGI script/program. The action specified within the form would be to call the page itself. Here is a simple Python example, assuming the name of your script is so_self_call.py:
#!/usr/bin/env python
import cgi
import sys
def end_page():
print "</body>"
print "</html>"
def print_form():
print "<form action=\"so_self_call.py\">"
print "<input type=\"text\" name=\"theText\">"
print "<input type=\"submit\">"
print "</form>"
return
def start_page():
print "Content-Type: text/html"
print
print "<html>"
print "<head>"
print "<title>Example of Python CGI script which calls itself</title>"
print "</head>"
print "<body>"
return
def main():
start_page()
print_form()
the_form = cgi.FieldStorage()
if "theText" in the_form:
print "From last time, theText = %s" % (the_form["theText"].value)
end_page()
return
if __name__ == "__main__":
sys.exit(main())