How do I create a function that is when I click the delete, it will ask me... in html - javascript

How do I create a function that is when I click the delete, it will ask me, if I click YES it will delete and, I click NO it won't delete and still stay that page.
I am using FLASK.
Here are my coding
<button class="button button2" style="float: right; font-size:30px;" onclick="deletefunction()">Delete it</button>
<script>
function deletefunction() {
if (confirm('Do you want to delete it?')) {
yourformelement.submit();
} else {
return false;
}
}
</script>

Here is an example of the jinga code :
<form action={{ url_for('delete_function') }} method=post>
<input type=hidden name="row_number" value="{{ row.number }}">
<button type="submit" onclick="return confirm('{{ 'Are you sure to delete ?'}}');return false;">{{"Delete"}}</button>
</form>
and in a working example:
from flask import Flask,request,abort,render_template_string
app = Flask(__name__)
#app.route("/", methods=["GET"])
def hello_world():
return render_template_string("""<!DOCTYPE html>
<html>
<head><title>Test</title></head>
<body>
<h1>Hello World</h1>
{% for number in [0,1,'b']%}
<h2>{{ number }}</h2>
<form action={{ url_for('delete_function') }} method=post>
<input type=hidden name="row_number" value="{{ number }}">
<button type="submit" onclick="return confirm('{{ 'Are you sure to delete ?'}}');return false;">{{"Delete"}}</button>
</form>
{% endfor %}
</body>
</html>
""")
#app.route("/delete-function", methods=["POST"])
def delete_function():
row_number = request.form['row_number'][:20]
try:
int_row_number = int(row_number)
except ValueError:
return abort(404)
return "Trying to delete row "+str(int_row_number)
if __name__ == '__main__':
app.run()

Related

How to create a comment box and comment display feature in flask?

Hi I am currently trying to create a comment box feature in flask. The problem I am facing is that when I click on the submit button, nothing happens. I want the user to be able to see the message they wrote along with their username below the comment box.
Here is my code:
python file:
from flask import Flask, render_template, request
import sqlite3
conn = sqlite3.connect('comments.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS comments
(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, comment TEXT)''')
conn.commit()
#app.route('/add_comment', methods=['POST'])
def add_comment():
name = request.form['name']
comment = request.form['comment']
c.execute("INSERT INTO comments (name, comment) VALUES (?, ?)", (name, comment))
conn.commit()
return render_template('comment.html', name=name, comment=comment)
#app.route('/')
def view_comments():
c.execute("SELECT * FROM comments ORDER BY id DESC")
comments = c.fetchall()
return render_template('index.html', comments=comments)
javascript file:
$(document).ready(function() {
$("#comment-form").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "{{ url_for('add_comment') }}",
data: $(this).serialize(),
success: function(data) {
$("#comments").append(data);
$("#name").val('');
$("#comment").val('');
}
});
});
});
html file:
<form id="comment-form" action="{{ url_for('add_comment') }}" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<label for="comment">Comment:</label>
<textarea id="comment" name="comment"></textarea>
<button type="submit">Submit</button>
</form>
<div id="comments">
{% for comment in comments %}
<div class="comment">
<p><strong>{{ comment[1] }}:</strong> {{ comment[2] }}</p>
</div>
{% endfor %}
</div
As you are returning a response from the post method (add_comment), you can skip AJAX use. Here is an example to load the comments on form submission.
app.py:
from flask import Flask, render_template, request, redirect, url_for
import sqlite3
app = Flask(__name__)
conn = sqlite3.connect('comments.db', check_same_thread=False)
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS comments
(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, comment TEXT)''')
conn.commit()
#app.route('/add_comment', methods=['POST'])
def add_comment():
name = request.form['name']
comment = request.form['comment']
c.execute("INSERT INTO comments (name, comment) VALUES (?, ?)", (name, comment))
conn.commit()
return redirect(url_for("view_comments"))
#app.route('/')
def view_comments():
c.execute("SELECT * FROM comments ORDER BY id DESC")
comments = c.fetchall()
return render_template('comment.html', comments=comments)
templates/comment.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Comments Example</title>
</head>
<body>
<form id="comment-form" action="{{ url_for('add_comment') }}" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<label for="comment">Comment:</label>
<textarea id="comment" name="comment"></textarea>
<button type="submit">Submit</button>
</form>
<div id="comments">
{% for comment in comments %}
<div class="comment">
<p><strong>{{ comment[1] }}:</strong> {{ comment[2] }}</p>
</div>
{% endfor %}
</div>
</body>
</html>
Output:

Raise an error in Django on specific field in form

In my Django/Python application I have fields which are necessary or not, depending on what is selected in previous fields. Thats why those are not mandatory by default. I would like to run a script which would raise an error on the chosen field, depending on the selection. I would like to do that when 'Submit' button is pressed, via script.
My html code:
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="POST" id="PostForm" data-sektor-url="{% url 'ajax_load_sektors' %}" novalidate enctype="multipart/form-data">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Report</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" id="submit" type="submit">Submit</button>
</div>
</form>
</div>
<script>
$("#submit").click(function () {
if (document.getElementById('id_res_person_1').value == '') {
HERE I WOULD RAISE AN ERROR ON THAT FIELD
}
});
</script>
You need to call a function when form is submitted, make your validation and if all good submit to the view
Here is an example:
JS
function validate(url) {
// do your validation
if(allIsOk){
// get the form
my_form.submit();
}
}
On Submit or link
<fom onsubmit="validate()">

Use Django if statement to run JavaScript on webpage

I want to show the image only if the output of the data comes out. So this JavaScript function should been executed only when data exists. Here is the code:
{% load static %}
<html>
<head>
<title>
Python button script
</title>
</head>
<body>
{% if data %}
{{data | safe}}
{% endif %}
<form action="/external/" method="post">
{% csrf_token %}
Input Text:
<input type="text" name="param" required><br><br>
<p id="demo" style="color:red">{{data_external}} {{data1}}
</p>
<img id="pic" src="{% static 'images/graph.png' %}" style="display:none;" />
<input type="submit" onclick="reloadimg();" value="Execute External Python Script">
</form>
</body>
</html>
<script>
function reloadimg(){
var src = "{% static 'images/graph.png' %}";
imageObject = document.getElementById("pic");
imageObject.style.display = 'inline-block';
imageObject.src = src;
}
</script>
How can I achieve such a result? If there is anything I needed to add to this question, just let me know.

Get the value of a variable from http get or post

I have this html page:
<head>
<h1>Prueba TFG</h1>
</head>
<body>
<form method="POST" action="">
Introduce KeyWord <input type="text" name="key">
<input type="submit" name="submit" value="Submit">
</form>
</body>
I would like get the value of "name", the input of the page, using JavaScript and pass this value to python. How can i do that?
Thank you so much!
You can use flask, a Python webframework, and utilize its builtin capability to access data from a request:
First, create your HTML and store in a file named user_input.html:
<html>
<head>
<h1>Prueba TFG</h1>
</head>
<body>
<form method="POST" action="/">
Introduce KeyWord <input type="text" name="key">
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
Then, create the routes with flask:
import flask
app = flask.Flask(__name__)
#app.route('/', methods=['GET', 'POST']):
def home():
if flask.request.method == 'POST':
keyword = flask.request.form['key']
#do something with keyword
return "<p>You entered {}</p>".format(keyword)
return flask.render_template('user_input.html')
However, to include javascript, you can use ajax with jquery to pass the variable to the script:
<html>
<head>
<h1>Prueba TFG</h1>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
Introduce KeyWord <input type="text" name="key" id='key'>
<button type='button' class='enter'>Submit</button>
<div id='result'></div>
</body>
<script>
$('document').ready(function(){
$('.enter').click(function(){
var value = $('#key').val();
$.ajax({
url: "/get_keyword",
type: "get",
data: {keyword:value},
success: function(response) {
$("#result").html(response);
$('#result').html(response);
},
error: function(xhr) {
}
});
});
});
</script>
</html>
In the app:
#app.route('/', methods=['GET', 'POST'])
def home():
return flask.render_template('user_input.html')
#app.route('/get_keyword')
value = flask.request.args.get('query')
return 'received value'

Making django html form perform 2 actions on submit

I'm working on a django web app, and there's an html form which I need to do 2 things when the form is submitted: create a record in the app's database and post some of the values collected to another website (e.g. a payment site).
The problem I'm having is getting the form to do the 2 things simultaneously. I know an HTML form can only have one action, and I've read some posts here on StackOverflow about using javascript to get the form to execute 2 or more actions, but everything I've tried so far hasn't worked for this situation. They all seem to get only one action to work.
This is what my django template looks like right now:
{% extends "some other template" %}
{% block content %}
<div>
...
<form id=form1" name="trans_form" method="POST" >
...
<!--DATA TO POST TO PAYMENT SITE-->
<input type="hidden" name="transaction_id" value="some value" />
<input type="hidden" name="transaction_amount" value="some value"/>
<input type="hidden" name="customer_id" value="some value" />
<input type="hidden" name="customer_name" value="some value" />
<!--DATA TO POST TO PAYMENT SITE-->
...
<!--DATA TO POST TO APP DATABASE-->
<input type="hidden" name="user" value="{{ user.id }}">
<input type="hidden" name="type" value="CC">
<input type="hidden" name="ref_no" value="{{ ref_no }}">
Amount: <input type="text" name="amount" id="id_amount" required />
Ref ##: <span>{{ ref_no }}</span>
Date: <span>{{ cur_date|date:'d/m/Y' }}</span>
Submit
<!--DATA TO POST TO APP DATABASE-->
...
</form>
...
</div>
{% endblock %}
{% block script %}
<script>
function submitForm()
{
createRecord(document.forms["trans_form"]);
sendToPay(document.forms["trans_form"]);
}
function sendToPay(f)
{
f.action= "www.paymentsite.com";
f.target = null;
f.onsubmit = null;
f.submit();
}
function createRecord(f)
{
f.action = "url to view that creates the record in database";
f.target = "_blank";
f.onsubmit = null;
f.submit();
}
</script>
{% endblock %}
What do you think? Am I trying to achieve the impossible? If not, point me in the right direction. Thanks.
Why not simply POST to the payment site from your controller:
def handle_payment(request):
post_to_payment_site(request)
write_payment_info_to_db(request)
def post_to_payment_site(request):
data = {'transaction_id': request.form['transaction_id',
# etc.
}
requests.post('payment-provider-url', data=data)
If you cannot accept POST data intended for your payment provider then you can do one of the following things:
Send your payment provider an XHR request - this requires that your payment provider properly implement CORS for the endpoint you are posting to. When that request completes, you can submit the form normally.
Change the target attribute of your form to point at an iframe or a new tab / window. Then, when the iframe loads, remove the target attribute, switch the action back to your endpoint and submit.
I finally solved my problem. I'm not sure it is the most efficient solution, but here it is.
I made one more HTML page to act as a middleman between my app and the payment site. It's a very simple page, practically a replica of the first form page but with only the required fields to be posted to the payment site. This way, there's no need for much JavaScript. Submitting the form creates a record in the app database, sends the needed data to the "middleman", which then posts the data to the payment site. The user never actually sees the middleman throughout the process.
Like I said, this might not be the most efficient solution, but it works fine.
First, here's the code for the views.py:
def write_payment_info_to_db(request):
dt = datetime.now()
form = Form()
err = False
if request.method == 'POST':
#Collect data to send to GTPay
transaction_id = request.POST['transaction_id']
transaction_amount = request.POST['transaction_amount']
customer_id = request.POST['customer_id']
customer_name = request.POST['customer_name']
#Create record in db for "valid" form data
form = Form(request.POST)
if form.is_valid():
form.save()
return render_to_response('middleman.html', {'transaction_id': transaction_id,
'transaction_amount': transaction_amount,
'customer_id': customer_id,
'customer_name': customer_name},
context_instance=RequestContext(request))
else:
err = form.errors
return ...
else:
return ...
And here's the middleman:
<html>
<body onload="document.submit2paymentsite_form.submit()">
<form name="submit2paymentsite_form" action="payment-provider-url" target="_self" method="POST">
{% csrf_token %}
<input type="hidden" name="transaction_id" value="{{ transaction_id }}" />
<input type="hidden" name="transaction_amount" value="{{ transaction_amount }}" />
<input type="hidden" name="customer_id" value="{{ customer_id }}" />
<input type="hidden" name="customer_name" value="{{ customer_name }}" />
</form>
</body>

Categories