Get data to a python variable from a html input? - python

I am new to python. I need to get data from a html input to a python variable. But I can't find a way to do this. It shows output as None, None, None for output.
It doesn't print out the data too. How can I fix this issue?
This is the code in html file.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type=text/javascript>
$(function() {
$('button#add-income').bind('click', function() {
$.getJSON('/add_income',
function(data) {
//do nothing
});
return false;
});
});
</script>
<form class="add-income-box" method="POST" action="">
<div class="add-income-expences-top-div">
<label>INCOME</label>
</div>
<div class="add-income-expences-label-div">
<label class="add-income-expences-date-lbl">Date : </label>
<label class="add-income-expences-details-lbl">Details : </label>
<label class="add-income-expences-amount-lbl">Amount : </label>
</div>
<div class="add-income-expences-input-div" id="div1">
<input class="add-income-expences-date-input" name="i_date" value="{{request.form.i_date}}">
<input class="add-income-expences-details-input" name="i_details" value="{{request.form.i_details}}">
<input class="add-income-expences-amount-input" name="i_amount" value="{{request.form.i_amount}}">
</div>
<button class="add-income-expences-bottom" id="add-income">ADD</button>
</form>
this is the code in python file
#app.route('/add_income', methods=["GET", "POST"])
def add_income():
i_date = request.form.get('i_date')
i_details = request.form.get('i_details')
i_amount = request.form.get('i_amount')
print(i_date)
print(i_details)
print(i_amount)
return "nothing"
output :-
None
None
None
127.0.0.1 - - [31/May/2020 16:56:07] "GET /add_income HTTP/1.1" 200 -

Change this form tag action attribute
<form class="add-income-box" method="POST" action="{{ url_for('update_project')}}">
In this way, when you click on button it will call the method specified in action attribute.
and if you want to call this API using AJAX then make use of JSON to send data. And if you want to send data using form then remove the Ajax code and change the code as above suggested and click on the button and you will not get the form data.

Related

django: request.POST.get() returns NoneType

I am work from data acquired from an html form.
I am currently failing to capture the data on the server side. Every input returns "NoneType" on the server.
I feel like I tried everything that I could find around here, notably changing id for name in the html form, nothing works.
here is what I got so far:
views.py:
def quadriatransport_simulationView(request):
return render(request, "simulation.html")
#csrf_exempt
def compute(request):
destination = request.POST.get("destination")
nombre_de_palettes = request.POST.get("nombre_de_palettes")
poids_par_palette = request.POST.get("poids_par_palette")
Optimisation_prix = request.POST.get("Optimisation_prix")
Optimisation_delai = request.POST.get("Optimisation_delai")
result = {"destination":destination}
print(result)
return JsonResponse({"operation_result": result})
results returns a dictionnary where destination is None
now here is what I have been able to do on the webpage
<form method="POST">
{% csrf_token %}
<label><h3>Input variables to calculate EOQ:</h3></label>
<br>
<br>
<span>Destination (departement) <input type="text" id="destination">
<br>
<br>
<span>Nombre de palettes <input type="text" id="nombre_de_palettes">
<br>
<br>
<span>Poids par palette <input type="text" id="poids_par_palette">
<br>
<br>
<span>Optimiser prix <input type="checkbox" id="Optimisation_prix">
<br>
<br>
<span>Optimiser délai de livraion <input type="checkbox" id="Optimisation_delai">
<br>
<input id="ajax-call" type="submit" value="Simuler">
</form>
<p id="ajax"></p>
and here is my js script inside of the webpage
<script>
document.querySelector("#ajax-call").addEventListener("click", event => {
event.preventDefault();
let formData = new FormData();
formData.append('destination', document.querySelector("#destination").value);
formData.append('nombre_de_palettes', document.querySelector("#nombre_de_palettes").value);
formData.append('poids_par_palette', document.querySelector("#poids_par_palette").value);
formData.append('Optimisation_prix', document.querySelector("#Optimisation_prix").value);
formData.append('Optimisation_delai', document.querySelector("#Optimisation_delai").value);
let csrfTokenValue = document.querySelector('[name=csrfmiddlewaretoken]').value;
const request = new Request('{% url "compute" %}', {
method: 'POST',
body: formData,
headers: {'X-CSRFToken': csrfTokenValue}
});
fetch(request)
.then(response => response.json())
.then(result => {
const resultElement = document.querySelector("#ajax");
resultElement.innerHTML = result["operation_result"];
})
})
</script>
Not sure what is wrong with this, I have successfully used the same structure for other projects and it worked. I have been struggling with it for hours that I can't see straight. Hopefully someone can see where I messed up!
You misspelled destination in your formData
formData.append('destination', document.querySelector("#destination").value);

Adding two numbers in flask

<html>
<head>
<title>Addition</title>
<script>
function display(id_name,result_name){
document.getElementById(result_name).innerHTML = document.getElementById(id_name).value;
}
function calculate(id1,id2,result_id) {
document.getElementById(result_id).innerHTML = parseInt(document.getElementById(id1).value)+parseInt(document.getElementById(id2).value)
}
</script>
</head>
<body>
<div class="input">
Enter 1st Number:
<input type="text" id="input1_text">
<button type="button" onclick="display('input1_text','input1')">Enter 1st Number</button>
<span id="input1"></span>
</div>
<div class="input">
Enter 2nd Number:
<input type="text" id="input2_text">
<button type="button" onclick="display('input2_text','input2')">Enter 2nd Number</button>
<span id="input2"></span>
</div>
<div class="result">
<button type="button" onclick="calculate('input1_text','input2_text','result_value')">Calculate</button>
<span id="result_value"></span>
</div>
</body>
</html>
so in the above code i am not only adding 2 nubmers but also displaying the numbers after pressing the button.so now what i am looking for is to make this using flask framework on pressing buttons their respective functions should be fired up and data should be updated.I have tried using forms so the problem is on clicking button of 1st number to display is whole page is refreshing and i am losing whole data.so now how do i write those functions in python and also making sure that the page should not reload.Also is it possible to reuse the display function based on the paramters rather than hard coding and writing 2 display functions for 2 numbers seperately
Unless you need to use the user inputted values in the backend of your application, you can simply perform the calculations in the front-end:
<html>
<body>
<p>Input first number:</p>
<input type='text' class='first_val'>
<p>Input second number:</p>
<input type='text' class='second_val'>
<div class='results'></div>
<button type='button' class='calculate'>Calculate</button>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('.calculate').click(function() {
var val1 = parseInt($('.first_val').val());
var val2 = parseInt($('.second_val').val());
var val3 = val1+val2;
$('.results').html('The result is '+val3);
});
});
</script>
</html>
Edit: using Python in the backend, ajax can be utilized:
index.html:
<html>
<body>
<p>Input first number:</p>
<input type='text' class='first_val'>
<p>Input second number:</p>
<input type='text' class='second_val'>
<div class='results'></div>
<button type='button' class='calculate'>Calculate</button>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
<script>
$(document).ready(function() {
$('.calculate').click(function() {
var val1 = $('.first_val').val();
var val2 = $('.second_val').val();
$.ajax({
url: "/get_numbers",
type: "get",
data: {val1: val1, val2:val2},
success: function(response) {
$(".results").html(response.packet);
},
error: function(xhr) {
//Do Something to handle error
}
});
});
});
</script>
</html>
Then, in the Python app:
#app.route('/', methods=['GET', 'POST'])
def home():
return flask.render_template('index.html')
#app.route('/get_numbers')
def get_values():
value1 = flask.request.args.get('val1')
value2 = flask.request.args.get('val2')
return flask.jsonify({'data':f'<p>The result is: {value1+value2}</p>'})
You should build an flask API function: a GET route which accepts the argument from your form and returns a JSON response object.
Then in your HTML when you click the button that should perform an AJAX GET quesry accessing your API route and return the values to that page. This avoids having Flask re-render your page and returns the data directly to your existing client web browser.
To make it easy to manipulate data dynamically in the webpage I suggest a JS framework like angular, react or vue. Personally I prefer vue since it can be self contained, loaded as script into the page and the setup is often minimal. The docs are also very easy and you can easily see how to link form input controls.

Getting button name as input

In this example I am assigning a variable (hsname) the school that is selected when sending the form:
<form class="w3-wide" action="/hschool" method="post">
<input list="hschools" name="hsname" autocomplete="off">
<datalist id="hschools">
<option value= "hs1">
<option value= "hs2">
</datalist>
<input type="submit">
</form>
I then use this value in python (with flask) and to get it I use the following (in a separated .py file):
hsname = request.form.get("hsname")
The previous is working fine.
In a similar way, I want to assign to a variable the name of the button that the user is clicking (b1 or b2). The following is not working as there is not variable that records the button that the user clicks.
<form class="w3-wide" action="/subject" method="post">
<button class="button button4" name="b1">b1</button>
<button class="button button4" name="b2">b2</button>
</form>
How can I do it?
I know I could use a radio button here but aesthetically I would rather use a normal button. I know I can use the onclick method but what should I write inside so that it stores a variable that is directly sent to flask?
If you want to send the info to the server as soons as the button is clicked, you can give a name and a value to an html <button> and those will be sent with the form:
<form class="w3-wide" action="/subject" method="post">
<button type="submit" name="clicked_btn" value="b1">b1</button>
<button type="submit" name="clicked_btn" value="b2">b2</button>
</form>
Once one of these buttons is clicked, the form will be submitted and the name and value (e.g. clicked_btn=b1) will be sent to the server (along with any other inputs in the form).
On the other hand, if you want to just remember the state of the button, so that it behaves like a checkbox or like a radio button, only to be sent to the server when a (different) submit button is clicked, then I suggest actually using a checkbox or a radio button and modifying its appearance using CSS to make it look like a button.
You can also use javascript to store some information into a <input type=hidden> input, which will later be sent to the server.
You can create an id for each button that can be captured on the client side send to the server via ajax:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<input type='text' id='value'>
<button class="button button4" name="b1">b1</button>
<button class="button button4" name="b2">b2</button>
</form>
<div id='user_results'></div>
<script>
$(document).ready(function() {
$('button').click(function(even){
var the_id = event.target.id;
var user_input = $('#value').val();
$.ajax({
url: "/get_user_data",
type: "get",
data: {btn: the_id, result:iuser_input},
success: function(response) {
$('user_results').html(response);
},
error: function(xhr) {
//Do Something to handle error
}
});
});
});
</script>
</html>
Then, in your .py file, create a route to receive the data from ajax:
#app.route('/get_user_data')
def get_data():
button_id = flask.request.args.get('btn')
user_input = flask.request.args.get('result')
return '<p>Thanks</p>'
You could put your button in a form with a hidden input and access the value with request.form.get("hsname") or request.POST.get("hsname) depending on how flask implements this (i'm more familiar with django).
Note that you will need 1 form+input per buttons
<form method="POST" action="some_url/">
<input type="hidden" name="hsname" value="the_name_of_the_button">
<button class="button button4" type="submit"></button>
</form>
EDIT: this is html 4.1, for html 5 see zvone's answer.

Ajax python how to post data

Sorry guys, maybe this has been asked before. But I googled around for several days and still cannot solve the problem. I am developing a chatting system using Google App Engine with Python. I would like the user to enter her/his message and click "Submit" button. That action will trigger an Ajax post function "addMsg()" to POST the message to class Chat (URL: "/chat"), which will add the message to datastore. There is another Ajax function "updateMsg()" which will update the message list periodically.
The code works fine for message updating, however, I am not able to post the message correctly. Can anybody help me? Thanks. Here are my codes:
chat.html:
<p>
<form method="" action="">
<input type="text" name="message" size="60" /><br />
<input type="button" value="Submit" onclick="addMsg('message')" />
</form>
</p>
<div id="chatcontent"> </div>
<script>
function addMsg(message) {
$.ajax({
type: "POST",
url: "/chat",
data: {'message': message},
cache: false
});
}
</script>
<script>
$(document).ready(function() {
function updateMsg() {
$.ajax({
url: "/message",
cache: false,
success: function(returndata){
$("#chatcontent").html(returndata);
}
});
setTimeout(updateMsg, 4000);
}
updateMsg();
});
</script>
message.html:
{% for chat in chatlist %}
<p>
{{ chat.text }} ({{ chat.user.account }}) {{chat.created|date:"D d M Y" }}
</p>
{% endfor %}
chat.py:
# Called by URL "/chat"
class Chat(webapp2.RequestHandler):
def post(self):
message = self.request.get('message')
newchat = ChatMessage(user=self.session['userkey'], text=message, created=datetime.datetime.now())
newchat.put()
# Called by URL "/message"
class Message(webapp2.RequestHandler):
def get(self):
que = db.Query(ChatMessage).order('-created')
chatlist = que.fetch(limit=100)
render(self, 'message.html', {'chatlist': chatlist})
# Note: render() is a function to be imported, which is just a normal template rendering function. It works fine and is omitted here.
Chat.html
<p>
<input type="text" name="message" size="60" /><br />
<input type="button" value="Submit" onclick="addMsg()" />
</p>
<div id="chatcontent"> </div>
<script>
function addMsg() {
var message = $('input[name=message]').val();
$.ajax({
type: "POST",
url: "/chat",
data: {'message': message},
cache: false
});
}
</script>

jQuery autocomplete doesn't want to send particular POST data

I'm trying to add an item (fund). The autocomplete succeeds in showing all the funds. It should retrieve the fund.id corresponding to that 'fund'. If I could get another set of eyes on this, it would be greatly appreciated...
Just to be clear: I'm not getting a specific error. My view just redirects if there is no 'fund' in the POST. I'm just trying to figure out why my autocomplete isn't posting the fund POST value' (fund.id).
-- Thank you advance
Template:
<script type="text/javascript" src="{{ STATIC_URL }}js/autocomplete/add_fund_autocomplete.js"></script>
...
<form method="POST" action="/profile/edit/">
{% csrf_token %}
<input type="hidden" name="fund" id="id_fund" />
<div class="inline-block">
<label for="id_omnibox">Fund</label>
<input id="id_omnibox" name="omnibox" placeholder="Enter a fund name or search for an existing..." type="text" />
</div>
<div class="input-prepend inline-block">
<label for="id_amount">Allocation</label>
<span>$</span>
<input id="id_amount" name="amount" type="text" placeholder="Enter amount" />
</div>
<button class="add" type="submit" name="add_position">Add</button>
</form>
add_fund_autocomplete.js:
$(document).ready(function() {
$.get('/autocomplete/funds/', function(data) {
var completions = new Array();
var dict = JSON.parse(data, function(key, value) {
completions.push(key);
return value;
});
$('#id_omnibox').autocomplete({
source: completions,
minLength: 2,
select: function(event, ui) {
$('#id_fund').val(dict[ui.item.value]);
}
});
});
});
(autocomplete)View:
#login_required
def funds(request):
funds = Fund.objects.exclude(name='Placeholder')
result = {}
for fund in funds:
result[fund.name] = str(fund.id)
return HttpResponse(json.dumps(result))
For example:
Adding the fund Hoth Ltd with an amount of $123.
Hoth Ltd's fund.id should be 1.
POST data
POST
---------------------------------------------------------
Variable Value
---------------------------------------------------------
fund u'' #empty? :\
csrfmiddlewaretoken u'436f77eb2023043be2f5242bb0443d80'
omnibox u'Hoth Ltd'
amount u'123'
add_position u'' #Just a trigger used in my view
The variable dict is undefined when the select callback function is called.
You can just use ui.item.value.

Categories