I'm building a web app right now that has a couple of text-fields that I would ideally like to be able to copy (individually) using a "copy" button next to each field. Right now I'm attempting to write a Pyperclip function in my main file, and then passing that as an onclick value for a button, but as soon as the page loads, the Pyperclip function executes and my clipboard is updated without pressing anything. So for example:
#app.route('/converted.html', methods = ['GET', 'POST'])
def converted():
pyperclip_Test = pyperclip.copy("apple")
return render_template('converted.html',
pyperclip_Test = pyperclip_Test)
Then in my template file:
Test
<div>Data that I want to copy</div>
I know the pyperclip function isn't copying that div - I retracted the original data that I can pass - but the problem still remains that the script executes without me pressing the button.
Any idea on how to get this working?
you cannot use pyperclip in a webpage ... you are confusing client side and serverside ... you are copying the text on the serverside clipboard, which does nothing for the client(or anyone else)
try something like the following (javascript)
<script>
function clip_text(a_string){
var input = document.createElement('input')
input.id="__copyText__";
input.value = a_string; // OOPS! document.getElementById(divId).innerText;
document.body.appendChild(input);
input.select();
document.execCommand("copy");
var txt = input.value
input.remove()
console.log("OK COPIED: '"+txt+"'")
}
function clip_div(divId){
return clip_text(document.getElementById(divId).innerText)
}
</script>
and then call it like this
Test
<div id="copyme">Data that I want to copy</div>
Related
I have a form with about 8 user inputs, I'm using Flask for this project. There is a button that calls a function in my python code that does XYZ, but it takes a bit of time, about 5 seconds. My problem is that if a user enters input, hits the button, and then enters more input (changes their inputs), the entire program crashes. I want to restrict user input until the function is done running
START <input type="text" name="set_start_freq" onchange="submit()" max="9999999999" value='{{template_data_dict["start_freq"]}}' disabled> <br><br>
STOP <input type="text" name="set_stop_freq" onchange="submit()" max="9999999999" value='{{template_data_dict["stop_freq"]}}' disabled> <br><br>
I have about 6 others that go along with this ^^
Adding disabled to the forms works to disable them, but not to re-enable them. I'm using
$(function() {
$("input").attr("disabled",false);
});
to reset the forms, making them 'enabled' once the page loads. Once another button is hit though, the forms are not re-disabled. I want the forms to be disabled while the page is loading, then re-enabled once the page is finished loading.
I've also tried disabling the entire form, that didn't get me anywhere.
Try to disable the button Until program function ends :
First add that when the button is pressed it is disabled .
Then in the function that takes 5-6 seconds write button enable code at the bottom.
def func():
# Write disable button code here
# Code that take 5-6 sec
# Write enable button code here
I don't know flask properly but know only basics hope that would give you an idea of how to do that.
This is what I ended up doing.
<script>
$('.button').click(function () {
$('input').removeAttr("disabled")
});
$('.button').click(function () {
$('input').attr("disabled", "disabled");
});
$(function() {
$(".auto_submit_item").change(function () {
$("config_form").submit();
});
});
</script>
I have a site using GCP python API, which is quite slow at making pull requests. So I have cached the area of the template using this data, and in the view I check if the cache is still active before making any more requests (not a copy n pasted code so if theres any typos ignore em :) )
def gcpProjectsView(request):
gcpprojects = None
cached_time = None
if cache.get(make_template_fragment_key('gcp')) is None:
cached_time=timezone.now()
gcpprojects = get_gcp_projects()
return render (request , 'gcp/gcpprojects.html', {'gcpprojects':gcpprojects,'last_update':cache_time})
To manually update the data, I have a refresh button that points to this view:
def refresh_gcp(request):
cache.delete(make_template_fragment_key('gcp'))
return redirect('gcpProjectsView')
The problem is that if the user clicks the refresh button 5 times the view makes 5 GCP Api calls, it needs to only do 1. How do I resolve this issue?
My suggestion would be to use a simple form with a button. Buttons can be disabled using simple javascript when clicked.
Because you're redirecting back to the same template in the view the button should be re-enabled again once it has 'refreshed'.
In this example snippet replace the action with whatever url routes to refresh_gcp.
<form method="GET" action="<url that points to refresh_gcp>">
<button type="submit" onclick="this.disabled = true;">Refresh</button>
</form>
This was the simplest solution I could think of that didn't involve implementing some sort of token validation for requests.
Use django session :
def refresh_gcp(request):
clicked = request.session.get("click")
if clicked:
return render(request,"your_html",{"disable":True})
# Set Button disable or not in your html by using context...
else:
request.session["click"]="user_click"
cache.delete(make_template_fragment_key('gcp'))
return render(request,"your_html",{"disable":False})
I am running an app using nodejs/electron and python.
I have 4 files: index.html, index.js, index.py and USER.py
In the index.html I have two buttons and a text input for specify an id of a user called 'idUser'.
In the index.js I have:
var spawn = require('child_process').spawn, py = spawn('python', ['index.py']),dataString = '';
py.stdout.on('data', function(data){
dataString += data.toString();
console.log(dataString);
});
py.stdout.on('end', function(){
console.log('answer=',dataString);
});
py.stdin.end();
In the index.py I have:
from USER import *
user=USER('user1','34')
And finally, in the USER.py I have:
class USER:
id=''
name=''
age=''
def __init__(self,name,age):
....blah blah blah...
def getName(self,id):
....blah blah blah....
def getAge(self,id):
....blah blah blah....
At the beginning of the execution using javascript (child_process) I create a python object called 'user' executing the javascript file, works perfecty. Now, here is the question:
I want to call user.getName(idUser) or user.getAge(idUser) with the buttons in the HTML whenever I want while I use the application.
Sincerelly I cannot figure out how to use the same object from different javascript files in order to use the information along the app.
I am building a front end which displays the row of data from sqlite database. For backend, I am using flask. I have a check button on the front end. What I need to do is to display the data one by one as I click the check button.
I would do something like this:
The first thing I would do would be to define an address in Flask that send the information that you want to the browser.
#app.route('/get_info')
def get_info():
df = query_your_db()
return df.to_json(orient = 'split')
And in javascript I would call this address when I press de button like this:
function render_info() {
console.log('render_info()');
$.post('get_info', function(data_json)
{
window.info= JSON.parse(data_json);
$('#name_div').append(info);
}
);
}
And the html button would be like this:
<a id="get_info_button" onclick="render_info()"></a>
Hope it helps you
currently trying to use flask and wtforms to make an html form.
My for template looks like this:
<ul><li>Description:</li>
<li> <textarea class="input" rows="10" cols="50" name="description" onKeyDown="limitText(this.form.description,this.form.countdown,150);"
onKeyUp="limitText(this.form.description,this.form.countdown,150);">
description of the article.You have characters left.
I wanted to use wtforms and just replace:
<textarea..> with {{form.description}}.
But then how do I incorporate the onkeydown event ? I need that to count the number of characters typed already in the textarea.
BTW. My form which I made using wtforms looks like this:
class ItemForm(Form):
title = TextField("Title")
subtitle = TextAreaField("Sub Title")
Description = TextAreaField("Description")
offervalue = FloatField("Offer Value")
imagefile_1 = FileField("Image File 1")
imagefile_2 = FileField("Image File 2")
imagefile_3 = FileField("Image File 3")
QUESTION: HOW SHOULD I STILL INCLUDE THE JAVASCRIPT TO ANY EVEN THAT HAPPENS IN THE TEXTAREA?
thanks for any pointer.
You'll want to use something to select the textarea and bind the keyboard events to it. I'd suggest jQuery like so:
$('textarea .input').keypress(function() {
limitText(this.form.description,this.form.countdown,150);
});
You can see the documentation for the keypress event here: http://api.jquery.com/keypress/ jQuery also can bind to keyup or keydown events.
If you aren't familiar with jQuery, this is a good place to start: http://docs.jquery.com/How_jQuery_Works
It looks like I'm a bit late, but my personal receipe is:
Keep your scripts in separate file, i.e. myscripts.js
Attach myscripts.js to required HTML page via <script
url="<path/to/myscripts.js>"></scripts>
Suppose you have function foo(eventObject) in myscripts.js, and element bar in target HTML-page.
Put into myscripts.js function linker(), that will glue these components (I use jQuery for this as example, but fill free to use plain JavaScript as well):
function linker() {
$(bar).on(event, function blablabla(eventObject) { foo(eventObject); })
}
Call linker() from your HTML page.