How to get value on drop box in Flask Python - python

I have a file XML. It's follow . I use Flask Framework Python to get query in search bar and value of current dropbox (e.g english or vietnamese). I use "POST" method get value when I enter or click "Search" button. But value of dropbox is null.
<form class="input-group">
<div class="input-group-btn search-panel" id="menu1">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
<span>Language</span>
</button>
<ul name ="btnLanguage" class="dropdown-menu" role="menu">
<li><a>English</a></li>
<li><a>Vietnamese</a></li>
</ul>
</div>
<input type="text" class="form-control" name="query" id ="query" placeholder="Search sentence...">
<span class="input-group-btn">
<button id ="btnSearch" class="btn btn-success" type="submit">
<span class="glyphicon glyphicon-search" aria-hidden="true"></span>
</button>
</span>
</form>
How can you help me. Thank you
#app.route("/search" , methods=["POST"])
def search():
print("True")
# read the posted values from the UI
_query = request.form['query']
print(_query)
_language = request.value['btnLanguage']
print(_language)
and Json Method:
$(function(){
$('#btnSearch').click(function(){
$.ajax({
url: '/search',
data: $('form').serialize(),
type: 'POST',
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
});
});

It is because ul-li is not a regular form control (Checkout this link for available form control in html). So jquery will not consider it when serializing form data. Solution : You need to write a script to append custom data with your form data or you should use <select> instead of ul-li dropdown.
Other problems with your code.
You are using click() event handler with a button having type submit so two events will occur, one is ajax you are calling and another is form will be submitted to server side with GET. To remove is issue you should be listening for form submit() event with preventing event propagation (check this answer).

Related

Am I able to get the text of a radio button in html to use in Flask?

I'm working on a simple web application that lets users rate and comment on movies, storing them in a database to be viewed later. The user inputs a movie to rate, and if that movie title is shared by multiple films, they are prompted to specify which of those films they meant. I've chosen to do this with radio buttons in my html file, but I can't figure out how to get the text of the button chosen and use it in Flask. The application takes the name of the film chosen and prints that name at the top of a different html file, but no matter what I do it always prints "None" instead of the chosen title.
I was able to find this answer: Get the text of the selected radio button in JQuery , which led me to try
var confirmed = $("input[name='confirmation']:checked").parent('label').text();
in my html script in order to obtain the text of the checked button. But when I try to request this in Flask it does not work.
confirm.html :
<div id="id02" class="modal" data-backdrop="false">
<form class="modal-content animate" action="/confirm" method="post">
<span onclick="document.getElementById('id02').style.display='none'" class="close" title="Close Modal">×</span>
<div class="container">
<h1>Please Specify Which Title to Rate:</h1>
{% for movie in multi %}
<label class="container">{{movie["title"]}} ({{movie["year"]}})
<input type="radio" id={{movie["year"]}} name="confirmation">
<span class="checkmark"></span>
</label>
{% endfor %}
<button type="submit">Rate</button>
</div>
<div class="container" style="background-color:#f1f1f1">
<button type="button" onclick="document.getElementById('id02').style.display='none'" class="cancelbtn">Cancel</button>
</div>
</form>
</div>
<script>
// Get the modal when page is loaded
$(window).on('load',function(){
$('#id02').modal('show');
});
var modal = document.getElementById('id02');
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
};
// variable storing the name of the film selected
var confirmed = $("input[name='confirmation']:checked").parent('label').text();
</script>
application.py :
#app.route("/confirm", methods=["GET", "POST"])
def confirm():
if request.method == "POST":
full = request.form.get("confirmed")
session["title"] = full # add movie title to session in order to use in rate function
return render_template("rate.html", full=full)
else:
return render_template("confirm.html")
I also have tried assigning an id to the button if it is checked in hopes of getting the text from the id, but when I tried this I just got "None" as well.
{% for movie in multi %}
<label class="container">{{movie["title"]}} ({{movie["year"]}})
<input type="radio" name="confirmation">
{% if checked=="checked" %}
<input type="hidden" id="confirmed" value="({{movie["year"]}})">
{% endif %}
<span class="checkmark"></span>
</label>
{% endfor %}
I'm very new to programming and this is my first time trying to make a web application, so any help on this is greatly appreciated!
When flask gives you a radio button value. It gives you the value attribute not the radio button text, so you only need to put value attributes to your radio buttons

Get data to a python variable from a html input?

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.

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.

can you change the way get method makes links for django?

I'm using django for a website that has a searchbar setup with a simple form:
<form method="get" action="/browse">
<div class="input-group col-md-12">
<input type="text" name="searchquery" class="form-control input-lg" placeholder="Search" style="margin-right:1vw; border-radius: 5px;"/>
<span class="input-group-btn">
<button class="btn btn-primary btn-lg" type="submit">
{% fontawesome_icon 'search' color='white' %}
</button>
</span>
</div>
</form>
This creates url's like this:
http://127.0.0.1:8000/browse/?searchquery=<searchquery>
However I've setup my django url like this:
http://127.0.0.1:8000/browse/<searchquery>/
I would like to use the second url (as it just looks a lot better in my opinion).
Is there a way I can make my form do this?
This isn't a question about Django. The browser simply can't do this with an HTML form. The action attribute of the form is set when it is loaded.
You could possibly write some JavaScript to make it do this. But that would be the wrong thing to do. Queries like search should be part of the querystring, not the URL.

Unknown code being added to HTML template when running local server

I was building a profile picture feature, it was working fine so I left it for a while, probably a week. I came back to it and ran the local server, but when I do there's a few lines that appear in the console. But do not exist on the source file.
Source file:
<script type='text/javascript'>
Dropzone.options.myDropzone = {
autoProcessQueue : false,
paramName: 'uploaded_image',
dictDefaultMessage: "Drag and drop files or click here to upload picture",
init: function() {
var submitButton = document.querySelector("#submitBtn")
myDropzone = this;
submitButton.addEventListener("click", function() {
myDropzone.processQueue();
});
// Automatically overwrites file so the user can only upload one
this.on("addedfile", function() {
document.getElementById('submitBtn').style.visibility = "visible";
});
this.on('addedfile', function(){
if (this.files[1]!=null){
this.removeFile(this.files[0]);
}
});
}
};
</script>
<!-- Modal -->
<div id="picModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close"></span>
<form action="{% url 'profile_test' %}" method='POST' enctype="multipart/form-data" class="dropzone" id="my-dropzone">{% csrf_token %}
<!-- submit button stays hidden by default, until user selects a picture -->
<button id='submitBtn' type='submit' class='pic-submit-button' style='visibility: hidden;'> Submit </button>
<input id='submit-all' type='file' name='uploaded_image'/>
{{form}}
</form>
</div>
</div>
Now the code I'm seeing when I run the server is only a few lines, and it's in the HTML that creates the modal:
<!-- Modal -->
<div id="picModal" class="modal" style="display: block;">
<!-- Modal content -->
<div class="modal-content">
<span class="close"></span>
<form action="/api/profile_test/" method="POST" enctype="multipart/form-data" class="dropzone dz-clickable" id="my-dropzone"><input type="hidden" name="csrfmiddlewaretoken" value="WDMihPq0zDhDQGaWxSFYyvxjtmxUxsBMpAzcDqVxDGUZj11O8wtqbCfCie1m81Tf">
<!-- submit button stays hidden by default, until user selects a picture -->
<button id="submitBtn" type="submit" class="pic-submit-button" style="visibility: hidden;"> Submit </button>
*****<input id="submit-all" type="file" name="uploaded_image">
<label for="id_user">User:</label><select name="user" id="id_user">
<option value="" selected="">---------</option>
<option value="2">Brian</option>
<option value="3">Charles</option>
</select>
<label for="id_img">Img:</label><input type="file" name="img" required="" id="id_img">
<div class="dz-default dz-message"><span>Drag and drop files or click here to upload picture</span></div></form>
</div>
</div>*****
The last chunk of code I put stars around is the code that is unknown to me. The Django project I cloned was using gulp, I talked to my friends and they said that it may have something to do with it, maybe it's doing something with Dropzone.js?. But why would it inject a random dropdown menu listing users in Django? I didn't use gulp myself because I just wanted to develop the feature, but that may have been a mistake.
Possibly the
{{form}}
is causing this issue.

Categories