python function with Django - javascript

Hey guys I have a problem,
I have next function in my views.py:
#userRegistered
def getSyncGit(request, section):
print 'POTATOE' #(<-debug print)
cmd = '. script.sh 1'
p = sp.Popen(['/bin/bash', '-c', cmd], stdout=sp.PIPE, stderr=sp.PIPE)
result = p.wait()
return HttpResponseRedirect(getURL(request.LANGUAGE_CODE, '/assistant/configuration/project/list/'))
At the urls.py:
from .views import getSyncGit
url(r'^/project/sync/$', getSyncGit, {'section':'configuracion'}, name='pgetSyncGit'),
And in my template:
<script type="text/javascript">
function sendSyncProject()
{
$.ajax({url: "{% url 'pgetSyncGit' %}", success: function(result){
alert('cool');
}});
}
</script>
<td>
<input id="butSendSyncProject" type="button" name="butSendSyncProject" style="margin-left:1px;" value="{% trans 'Sinc' %}" onclick="sendSyncProject()" />
</td>
<td>
asdasdasdasdasddas
</td>
When I call to action with button, I can see thealert message, but the getSyncGit function is not executed.
When I call to action with url href, it redirects me to the url "/project/sync/", but the function neither executes....

Try to change your script to a script that writes a line into a file like "echo 'test' > tmp.txt" and tell us if tmp.txt is being created or not

Thank you for your answer #Oliver
I've tried what you've said and it doesn't work.
I've tried the following:
At the urls.py:
from .views import editDeProject
url(r'^/project/edit/0', editDeProject, {'section':'configuracion'}, name='pgetSyncGit'),
And now i have next function in my views.py:
def editDeProject(request, id, section):
"""Page Edit of DB de_project"""
errorTable = ''
form = None
if id == 0:
getSyncGit(request,id,section)
else:
try:
table = DeProject.objects.get(codProject=id)
if request.method == 'POST':
Using this method it works, it prints POTATOE and it generates file.txt, however I'm forcing url.py to take id 0 as an input.
therefore I believe the problem is when the (r'^/project/sync/(?P.*)/' gets generated

Related

How to fetch data from the database in Django on clicking submit?

I need to get database objects on the HTML only when the the SUBMIT is clicked and not on page load. I currently have an AJAX script running on the same form where it returns the text entered in textbox onto the HTML when submit is clicked. I want this feature to stay as well as add a new feature of retrieval of data. Below are some of the code snippets I am using:
views.py
#csrf_exempt
def chat(request):
resps = Responses.objects.all()
context = {'resps' : resps}
return render(request, "chat.html", context)
urls.py
path('chat/', views.chat, name='chat'),
chat.html
<form id="testForm" name="test-form" class="test-form" action="" method="POST">{% csrf_token %}
<input id="texting" name="texting" type="text" class="test-text" placeholder="Test here"/>
<div class="footer">
<input type="submit" value="SEND">
</form>
</div>
{% for r in resps %}
<div>
<p>{{r.response}}</p>
</div>
{% endfor %}
................................................
<script type="text/javascript">
$(document).on('submit','#testForm', function(e){
e.preventDefault();
$.ajax({
type : 'POST',
url : '/chat/',
data :{
text : $('#texting').val(),
csrfmiddlewaretoken: $('input[text=csrfmiddlewaretoken]').val()
},
success : function(){
// alert("Done!");
document.getElementById("userSpeaks").innerHTML = document.getElementById('texting').value;
}
});
});
</script>
Any help would be appreciated. I just need a way out to print the model objects on each click of the submit button and not automatically on page load. Thanks in advance.
Please change the line
csrfmiddlewaretoken: $('input[text=csrfmiddlewaretoken]').val()
to
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
So you will have to send your querylist as a json object if you want it to be sent through ajax
from django.http import JsonResponse
from django.core.serializers import serialize
#csrf_exempt
def chat(request):
data = {
'resps': serialize("json", Responses.objects.all())
}
return JsonResponse(data)
and you success will look something like this
success : function(data){
// alert("Done!");
resps = JSON.parse(data.resps);
var htmldata=""
for(var x in resps){
htmldata+="<p>"+resps[x].fields.xyz+"</p>"
}
$("#userSpeaks").html(htmldata);
}

Get user input and output Flask and HTML

I'm trying to develop a web-app with Flask and HTML and right now I need to get the user input, pass it to the Python back-end, execute a function and return its output, placing it inside an HTML element. I also want this to happen without refreshing the HTML page.
How can I do this?
Bellow I have the code that I've developed so far but it's not working correctly:
My HTML:
<div id="ThroughputRate" class="data_entry">
<form action="{{ url_for('background_check_throughputrate') }}" method="post">
<input name="throughput_rate_text" class="input_box">
<input id="checkThroughputRate" type="submit" class='new-button-data' value="Check Throughput Rate">
<output name="throughputRateResult" class="result_box" ></output>
</form>
</div>
My Flask backend:
#app.route('/background_check_throughputrate', methods=['GET', 'POST'])
def background_check_throughputrate():
if request.method == 'POST':
text = request.form['throughput_rate_text']
processed_text = str(text)
throughput = transition_throughput_rate(processed_text)
return jsonify(throughput)
My HTML (continuation to get the output of the function executed on Flask):
<script type=text/javascript>
$(function() {
$('a#checkThroughputRate').bind('click', function() {
$.getJSON('/background_check_throughputrate', function(data) {
console.log(data);
document.getElementById('throughputRateResult').innerHTML = data;
});
return false;
});
});
</script>
The idea behind my execution is that the user uses the first snippet of code (in HTML) to insert the input, this input is passed onto the second snippet of code (in flask) and finally, the output of the function is passed onto the last snippet of code (in JS inside HTML) so that it can be displayed on the corresponding HTML element.
So far, the input is being correctly processed inside flask but the issue is that when the function returns the jsonify, it appears on the screen, instead of sending it into the frontend. What am I doing wrong?
Thank you all
$.getJSON is designed to load the JSON data from endpoint using GET request, however, your Python code example responds to only POST requests.
Here is the working code:
HTML
<div id="ThroughputRate" class="data_entry">
<form action="{{ url_for('background_check_throughputrate') }}" method="post" id="throughputRateForm" enctype="multipart/form-data">
<input name="throughput_rate_text" class="input_box">
<input id="checkThroughputRate" type="submit" class='new-button-data' value="Check Throughput Rate">
<output id="throughputRateResult" class="result_box" ></output>
</form>
</div>
Python
#app.route('/background_check_throughputrate', methods=['GET', 'POST'])
def background_check_throughputrate():
if request.method == 'POST':
text = request.form['throughput_rate_text']
processed_text = str(text)
throughput = transition_throughput_rate(processed_text)
return jsonify(throughput)
JavaScript
<script type="text/javascript">
$(function () {
$('#throughputRateForm').on('submit', function (e) {
e.preventDefault();
var form = $(this)[0];
var formData = new FormData(form);
$.ajax({
url: '/background_check_throughputrate',
method: 'POST',
data: formData,
processData: false,
contentType: false,
success: function (data) {
console.log(data);
document.getElementById('throughputRateResult').innerHTML = data;
}
});
});
});
</script>
Also, this code blindly trusts the user input and displays it on the webpage which can result to Cross-Site Scripting (XSS) and that is not good!
Avoid using innerHTML property when displaying user input, because it can be used to inject malicious HTML tags (e.g. <script>), i would highly recommend using innerText property instead.

FLASK - AJAX GET data from database

I am making a "write anything here" webpage where users can write anything in a textbox then post it and it is visible to everyone. It worked fine till I found out that when any user writes and submits, all the others have to refresh the page so as to get the new data from database. So a solution to this was to call ajax continuously in some intervals. This would check if there are new entries in the table. If yes, then it would render it to the html without refreshing the whole page. Now I am pure ajax noob and after hours of research I am unable to find out how to do it.
Here is the html code
<div id="textArea">
<form action="http://127.0.0.1:3000" method="POST">
<br>
<textarea minlength="3" name="comment" placeholder="Enter Text Here.." required></textarea>
<input id="postButton" type="submit" name="" value="POST">
</form>
</div>
</div>
<div class="show">
{% for item in data %}
<div id="auto" class="disPost">{{item[0]}}</div>
{% endfor %}
</div>
Here the textarea is in a form and it submits the text to database via flask server.
Also, all the comments that users wrote are shown in "div.show"
Now the flask code is like this
#app.route('/', methods = ['POST', 'GET'])
def home():
if request.method == 'POST':
post = request.form["comment"]
myquery = "select p_id from posts order by p_id desc limit 1"
mycursor.execute(myquery)
new_p_id = mycursor.fetchone()[0] + 1
myquery = "select exists(select * from posts where p_des=%s)"
rec_tup = (post,)
mycursor.execute(myquery, rec_tup)
if mycursor.fetchone()[0]==0:
myquery = "insert into posts values(%s, %s)"
rec_tup = (new_p_id, post)
mycursor.execute(myquery, rec_tup)
mydb.commit()
mycursor.execute("select distinct p_des from posts order by p_id desc")
data = mycursor.fetchall()
return render_template("homepage.html", data=data)
"mydb" is the connector & "mycursor" is the connector's cursor
Now I am stuck somewhere in how to call AJAX function. I am not able to write beyond this ..
$(document).ready(function() {
setInterval(function() {
$.ajax({
url: '',
type: 'GET',
data: //something must be here,
success: function(data) {
//here "div" must be added to the "show" class - that is comment of other users
}
})
}, 3000);
});
I know that I have to do something like this but am literally not able to solve it.
I know this is not good question and I must look at tutorials first. But believe me I had it all. I am not able to solve this problem at all.
Thank you for seeing this :)
I did this on my latest project, you can try it too. But make sure to refresh only div element you want the data show, not all the page.
$(document).ready(function() {
function getData(){
$.ajax({
url: '',
type: 'GET',
data: //something must be here,
success: function(data) {
//here "div" must be added to the "show" class - that is comment of other users
}
});
}
getData();
setInterval(function() {getData()},2000);
});

Displaying the result of ML model on Web page

I am exploring RESTful Flask API and as a learning I have created a small web form in HTML. Please see below the code for HTML.
<!DOCTYPE html>
<html>
<h2>User Input</h2>
<body
<script>
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script src="/static/js/predict.js"></script>
<p>Please enter the Power prices per unit</p>
<form method="get" action='/predict' target ="_blank"
enctype="multipart/form-data">
New Value - 1:<br>
<input type="number" id="New_val_1">
<br>
New Value - 2:<br>
<input type="number" id="New_val_2">
<br><br>
<button id="btnpredict" type="button">Predict</button>
</form>
<p>If you click the "Submit" button, the form-data will be sent to a page
called "/action_page.php".</p>
</body>
</html>'
Please see below the code for predict.js. This is a JQuery AJAX
$(function(){
$('#btnpredict').click(function(){
$.ajax({
url: '/predict',
data: JSON.stringify({userInput: uInput})
type: 'GET',
contentType: 'application/json',
success: function(response){
("#results").text(response.results);
},
error: function(error){
console.log(error);
}
});
});
});
And finally, the app.py code where the above HTML is getting rendered and upon receiving the the values passed on forms ML model is used.
from flask import Flask, redirect, request, render_template,json, Response
import statsmodels.api as sm
import numpy as np
from sklearn.externals import joblib
app = Flask(__name__)
#app.route('/')
#app.route('/home')
def home():
return render_template('index.html')
#app.route('/predict', methods = ['GET'])
def predict():
if request.method=='GET':
X_value_new_1 = request.values.get('New_val_1')
X_value_new_2 = request.values.get('New_val_2')
X_1,X_2 = X_value_new_1,X_value_new_2
testData = np.array([X_1,X_2]).astype(np.float).reshape(-1,1)
testData=sm.add_constant(testData)
pred = Regression_model.predict(testData)
dump = json.dumps({'prediction':list(pred)})
resp = Response(dump,mimetype='application/json')
return resp
return None
def load_model():
global Regression_model
Regression_model = joblib.load('E:/model_file_save')
if __name__ == "__main__":
print("**Starting Server...")
load_model()
app.run(debug=True)
Now the problem:
When I click on Predict button nothing happens. However, if on the address-bar if I write the 'http://localhost:5000/predict?New_val_1=1000&New_val_2=2000' then I get the correct prediction values in JSON format.
How to fix this issue? Is there any problem in JQuery?
Please help.
Best
AR
Read textbox values e.g. $("#tag").val() and concate with ajax url e.g.
predict?New_val_1=1000&New_val_2=2000'
and remove data property. You can also pass values using data property see below link for example.
https://www.codeproject.com/Questions/870797/How-to-pass-textbox-value-to-other-page-using-Jque

Django: create a "changing button" or waiting page

I have an external python program, named c.py, which "counts" up to 20 seconds.
I call it from my Django app views.py and in the html page I have a button to start it. It's ok (= in Eclipse I can see that c.py prints 0,1,2,3,...20 when I press the button on the webpage) but I would like that the button changes from "GO" to "WAIT" during c.py process (or I would like to perform a waiting page during the counting or also a pop-up).
c.py
import time
def prova(z):
z = 0
while z < 20:
time.sleep(1)
z = z + 1
print(z)
views.py
from django.shortcuts import render_to_response
#etc.
import c
def home_user(request):
return render_to_response('homepage/home.html',{'user.username':request}, context_instance = RequestContext(request))
def conta(request):
c.prova(0)
return redirect(home_user)
where in homepage.html I have the "GO" button that I would like to change in "WAIT" if the function conta is running.
urls.py
urlpatterns =patterns('',
url(r'^homepage/home/$', views.home_user, name='home'),
#etc.
url(r'^conta', views.conta, name='conta'),
)
home.html
{% if c.alive %}
WAIT
{% else %}
GO
{% endif %}
I don't put the whole code.. I hope this is sufficient to understand my trouble.
I also see at How to create a waiting page in Django but I would start with something simpler.
Up to now when I start c.py I see that my web page is loading something (=it is "counting") but my button does not change and, after c.py execution, I return to 127.0.0.1:8000/homepage/home/ page.
Is the problem in html or in my function definition or both?
UPDATE
I try to simplify the question:
I found this script...
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var text = "";
var i = 0;
while (i < 10) {
text += "<br>The number is " + i;
i++;
}
document.getElementById("demo").innerHTML = text;
}
</script>
I would like to "import" my conta() function in while instead of the cicle with i++
i.e. I would like to have a similar thing:
while conta() is running, appear something like Waiting.. and when it stop i return to my home page.. I don't know how "put" conta() in the script.. is this possible? Am I a dreamer? :)
You're trying to check a server-side value on the client, but the problem is that the if c.alive statement only gets evaluated when your view is rendered - not as the status of c changes.
You would need to be able to report back the status of c to the client via ajax long polling or WebSockets, or, if you don't care about the incremental status of c and just want to change the text of the link, you'll need to use JavaScript to set the value when the click event of the link fires:
// assuming jQuery for brevity...
$(document).ready(function() {
// avoid hard-coding urls...
var yourApp = {
contaUrl: "{% url 'conta' %}"
};
$('#btnGo').click(function(e) {
e.preventDefault(); // prevent the link from navigating
// set css classes and text of button
$(this)
.removeClass('btn-primary')
.addClass('btn-danger')
.text('WAIT');
$.get(yourApp.contaUrl, function(json) {
window.top = json.redirect;
});
});
});
but... your conta function will need to return a JsonResponse instead of an HttpResponse in order to do the redirect on the client-side:
from django.core.urlresolvers import reverse
from django.http import JsonResponse
def conta(request):
c.prova(0)
redirect = reverse('name_of_home_user_view')
return JsonResponse({'redirect': redirect})
I post my working solution. Thanks to #Brandon for the useful answer.
in conta.js some changes:
$(document).ready(function() {
// avoid hard-coding urls...
var yourApp = {
contaUrl: "/conta/"
};
$('#btnGo').click(function(e) {
e.preventDefault();
// set css classes and text of button
$(this)
.removeClass('btn-primary')
.addClass('btn-danger disabled') // with *disabled* I'm sure that the button is not clickable
.text('WAIT');
$.get(yourApp.contaUrl, function(json) {
alert("I have finished counting");
parent.window.location.reload(true);
});
});
});
in views.py
def conta(request):
c.prova(0)
redirect = reverse('home')
return JsonResponse({'redirect': redirect})

Categories