How to get values from select form to a python file with Flask - flask

I've created a select options with html and templating in flask.
What I need to accomplish is to take the option values and put it inside my code, here is my html code :
<select id="oblast_select" name='areaid'>
<option value="0">0</option>
<option value="5971">value1</option>
<option value="7402">value2</option>
<option value="5219">value3</option>
<option value="4949">value4</option>
<option value="5764">value5</option>
<option value="7412">6</option>
<option value="6217">value7</option>
<option value="6802">value8</option>
<option value="6940">value9</option>
</select>
Also here is my java code that sends post request to python file:
var serviceid = document.getElementById("name_street").value;
var areaid = document.getElementById('oblast_select').value;
$(".btn").addClass("clicked");
$.post(
"/serviceidlookup",
{ serviceid: serviceid },
{ areaid: areaid }
).done(function (reply) {
$(".spinner").css("display", "block");
$('.spinner').fadeOut(5500);
setTimeout(function() {
$('#reply').empty().append(reply).fadeIn(3000);
}, 4000);`enter code here`
});
and finally my python file run.py:
#app.route('/serviceidlookup', methods=["GET", "POST"])
def serviceidlookup():
reload(sys)
sys.setdefaultencoding("utf-8")
sys.stdout.encoding
serviceid = request.form.get('serviceid')
areaid = request.args.get('areaid')
idarea = str(areaid)
con = psycopg2.connect(**config)
cur = con.cursor()
cur.execute("select ate,ate_type,name_kg,name_ru,name_en,parent from ate_history where ate in (select ate from street_ate where street in (select street from street_history where name_ru = '%s') and parent = %s)" %(serviceid,idarea))
entries = [dict(ate=row[0], ate_type=row[1], name_kg=row[2], name_ru=row[3], name_en=row[4], parent=row[5]) for row in cur.fetchall()]
return render_template('lookup.html', serviceid=serviceid, entries=entries)
After running this code, in the terminal gives me this error :
**LINE 1: ...om street_history where name_ru = 'None') and parent = None)**
infact, i get the serviceid value from the input field that i've created, it didn't get the other value which is in our case on of the options so for example 7402 to be inside the query at this part :
and parent = %s)"
Please any help would be toooooooons appreciated !!!!!!!

You have written
serviceid = request.form.get('serviceid')
areaid = request.args.get('areaid')
Try changing areaid to match the serviceid i.e
serviceid = request.form.get('serviceid')
areaid = request.form.get('areaid')
Edit: Try replacing
var areaid = document.getElementById('oblast_select').value;
with this..
var e = document.getElementById("oblast_select");
var areaid= e.options[e.selectedIndex].value;
Edit2: Change your jQuery post to this..
$.post(
"/serviceidlookup",
{ serviceid: serviceid },
{ areaid: areaid } , function (reply) {
$(".spinner").css("display", "block");
$('.spinner').fadeOut(5500);
setTimeout(function() {
$('#reply').empty().append(reply).fadeIn(3000);
}, 4000);
});

According to the Flask docs - http://werkzeug.pocoo.org/docs/0.10/datastructures/#werkzeug.datastructures.MultiDict the request.args.get() method will only return the first element by default. To get all the values you need to use a list method; request.args.getlist().

Related

How to get the ID of record in another html?

why i cant get the ID of payment type, even i already print the ID in the html?
in my first html (elementary.html) I have this code
<select name="gradelevel" id="gradelevel" onchange="ChangeYearList(this.value)">
<option">-- Education Level --</option>
{% for ylvl in edulevel %}
<option value="{{ylvl.id}}">{{ylvl.Description}}</option>
{% endfor %}
</select>
<div id="txtHint" class="scale-in-center" width="100%"></div>
<script>
function ChangeYearList(str) {
var xhttp;
var x = document.getElementById("gradelevel").value;
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
document.getElementById("demo").innerHTML = x;
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xhttp.open("GET", "{% url 'paymentElementary' %}?payments_ID="+str, true);
xhttp.send();
}
</script>
this is my views.py
def paymentElementary(request):
paymentsid = request.GET.get('payments_ID')
payment = ScheduleOfPayment.objects.filter(Education_Levels=paymentsid).order_by('Payment_Type').distinct('Payment_Type')
return render(request, 'accounts/paymentElementary.html', {"payment":payment})
This is my second html (paymentElementary.html)
<select id="payments" name ="payments">
<option value="0">-- Payment Type --</option>
{% for paymentschedule in payment %}
<option value="{{paymentschedule.Payment_Type.id}}">{{paymentschedule.Payment_Type.id}}. {{paymentschedule.Payment_Type}}</option>
{% endfor%}
</select>
this is what it looks like in web view
it works like a charm. but when i tried to save it into my database
id = request.POST.get('payments')
payment = PaymentType(id=id)
V_insert_data = StudentsEnrollmentRecord.objects.create(
Payment_Type=payment
)
this is the error
this is the full traceback
update view.py file in this way
def paymentElementary(request):
paymentsid = request.GET.get('payments_ID')
payment = ScheduleOfPayment.objects.get(Education_Levels=paymentsid).order_by('Payment_Type').distinct('Payment_Type')
return render(request, 'accounts/paymentElementary.html', {"payment":payment})

Add Calendar Widget to Django Form

I have a view on my website that uses a couple of Django forms to allow the user to specify a date range. I was able to get it so that one Django form creates a start and end field and that when the user clicks on those fields a calendar widget (from here) pops up that allows the user to select a date range. However, when the user selects the date range and hits "apply" the form fields aren't updated.
EDIT
The form I'm using looks like this:
class DateRangeForm(forms.Form):
def __init__(self, *args, **kwargs):
initial_start_date = kwargs.pop('initial_start_date')
initial_end_date = kwargs.pop('initial_end_date')
required_val = kwargs.pop('required')
super(DateRangeForm,self).__init__(*args,**kwargs)
self.fields['start_date'].initial = initial_start_date
self.fields['start_date'].required = required_val
self.fields['end_date'].initial = initial_end_date
self.fields['end_date'].required = required_val
start_date = forms.DateField()
end_date = forms.DateField()
The view they are used in looks like this:
def table_search(request):
initial_start = "2015/2"
initial_end = "2015/222"
message = {'last_url':'table_search'}
if request.method == "POST":
daterange_form = DateRangeForm(request.POST,required=True,initial_start_date=initial_start,initial_end_date=initial_end)
else:
daterange_form = DateRangeForm(required=True,initial_start_date=initial_start,initial_end_date=initial_end)
search_dict.update({'daterange_form':daterange_form})
return render(request, 'InterfaceApp/table_search.html', search_dict)
The Django template here:
<div class="container">
<form action="/InterfaceApp/home/" method="post" class="form">
{% csrf_token %}
<div class="daterangepicker-container mcast-search-filter">
<div class="daterangepicker-label">Date range:</div>
<div id="daterange" class="daterangepicker-content">
{% bootstrap_form daterange_form %}
<i class="icon-calendar icon-large"></i>
</div>
</div>
</form>
</div>
<script>
// the start_date and end_date are the ids that django form fields created
$("#daterange").daterangepicker({
locale: {
format: 'YYYY-MM-DD'
},
startDate: '{{daterange_form.start_date.value}}',
endDate: '{{daterange_form.end_date.value}}'
});
</script>
EDIT 2
And the forms currently look like this (after #ShangWang suggestion) rendered:
Is there a way to display it so the start and end date fields show up? I tried changing the div class so it wasn't hidden, and then they showed up but seemed superfluous.
I use bootstrap-daterangepicker: https://github.com/dangrossman/bootstrap-daterangepicker. It would bind the widget's change to your django form field, so you don't need to manipulate the data once it comes to the views.py.
To get more details you should download and play with it, but here's a rough idea:
Your form.py:
class DateRangeForm(forms.Form):
start_date = forms.DateField()
end_date = forms.DateField()
def __init__(self, *args, **kwargs):
# initialize the start and end with some dates
Your template:
<div class="daterangepicker-container mcast-search-filter">
<div class="daterangepicker-label">Date range:</div>
<div id="daterange" class="daterangepicker-content">
<i class="icon-calendar icon-large"></i>
<span></span> <b class="caret"></b>
</div>
</div>
<!-- This is a hidden div that holds your form fields -->
<div class="hide">From {{ daterange_form.start_date }} to {{ daterange_form.end_date }}</div>
To trigger the widget you need a javascript binding:
// the id_start_date and id_end_date are the ids that django form fields created
$("#daterange").initDateRangePicker("#id_start_date", "#id_end_date");
I created a datepicker wrapper, and defined the initDateRangePicker function. You should put following code in a file called daterangepicker.js and import that in your template as well(or simply copy it into your template):
(function($) {
$.fn.initDateRangePicker = function(start_date_el, end_date_el, future) {
return this.each(function() {
var start = moment($(start_date_el).val());
var end = moment($(end_date_el).val());
var display_date = function(start, end) {
var str = ""
str += start.format('MMMM Do, YYYY');
str += " - ";
str += end.format('MMMM Do, YYYY');
return str;
};
$(this).find("span").html(display_date(start, end));
var self = this;
if(!future) {
$(this).daterangepicker({
format: 'YYYY-MM-DD',
timePicker: false,
ranges: {
'Last 7 days': [moment().subtract('days', 6), moment()],
'Month to date': [
moment().startOf('month'),
moment(),
],
'Last Month': [
moment().subtract('month', 1).startOf('month'),
moment().subtract('month', 1).endOf('month'),
]
},
}, function(start, end) {
$(start_date_el).val(start.format('YYYY-MM-DD'));
$(end_date_el).val(end.format('YYYY-MM-DD'));
$(self).find("span").html(display_date(start, end));
});
}
else {
$(this).daterangepicker({
format: 'YYYY-MM-DD',
timePicker: false,
ranges: {
'Next 7 days': [moment().add('days', 1), moment().add('days', 7)],
'Next month': [
moment().add('month', 1).startOf('month'),
moment().add('month', 1).endOf('month'),
],
},
}, function(start, end) {
$(start_date_el).val(start.format('YYYY-MM-DD'));
$(end_date_el).val(end.format('YYYY-MM-DD'));
$(self).find("span").html(display_date(start, end));
});
}
});
};
}).call(this, jQuery);

Ajax dont works populating a form

Hey anyone can help me with this problem ?
I have this issue with my code, two files:
1 - test.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Documento sin título</title>
<script>
var url = "getagentids.php?param=";
function handleHttpResponse() {
if (http.readyState == 4) {
results = http.responseText.split(",");
document.getElementById('formality').value = results[0];
document.getElementById('fullname').value = results[1];
document.getElementById('sex').value = results[2];
document.getElementById('id').value = results[3];
document.getElementById('joindate').value = results[4];
document.getElementById('jobtitle').value = results[5];
document.getElementById('city').value = results[6];
document.getElementById('typeofsalary').value = results[7];
document.getElementById('contract_type').value = results[8];
}
}
function getagentids() {
var idValue = document.getElementById("email").value;
var myRandom=parseInt(Math.random()*99999999); // cache buster
http.open("GET", url + escape(idValue) + "&rand=" + myRandom, true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
}
function getHTTPObject() {
var xmlhttp;
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
var http = getHTTPObject();
</script>
</head>
<body>
<form name="schform">
<table bgcolor="#dddddd">
<tbody>
<?php
echo $param;
include '../../../connect.php';
$db =& JFactory::getDBO();
$query = "SELECT email FROM dbemployeekpw";
$db->setQuery($query);
$result = $db->loadObjectList();
$email = $result[0];
echo " <select size='1' name='email' id='email' onChange='getagentids()' required >
<option value=''> Seleccione </option>";
foreach($result as $email)
{
echo "<option value='".$email->email."'>".$email->email."</option>";
}
echo "</select>"
?>
<tr><td>Formality</td><td><input id="formality" type="text" name="formality"></td></tr>
<tr><td>Fullname</td><td><input id="fullname" type="text" name="fullname"></td></tr>
<tr><td>Sex</td><td><input id="sex" type="text" name="sex"></td></tr>
<tr><td>Id</td><td><input id="id" type="text" name="id"></td></tr>
<tr><td>Joindate</td><td><input id="joindate" type="text" name="joindate"></td></tr>
<tr><td>Jobtitle</td><td><input id="jobtitle" type="text" name="jobtitle"></td></tr>
<tr><td>City</td><td><input id="city" type="text" name="city"></td></tr>
<tr><td>Typesalary</td><td><input id="typeofsalary" type="text" name="typeofsalary"></td></tr>
<tr><td>Contract Type</td><td><input id="contract_type" type="text" name="contract_type"> </td></tr>
<tr><td><input size="60" type="reset" value="Clear"></td><td></td>
</tr>
</tbody></table>
</form>
</body>
</html>
and..
2 - getagentids.php
<?php
//$param = $_GET["param"];
include '../../../connect.php';
$db =& JFactory::getDBO();
$query = $db->getQuery(true);
$query = "SELECT * FROM dbemployeekpw WHERE email = 'camilo.uribe#kantarworldpanel.com'";
$db->setQuery($query);
$results = $db->loadObjectList();
foreach ( $results as $result )
{
$formality = $result->formality;
$fullname = $result->fullname;
$sex = $result->sex;
$id = $result->id;
$joindate = $result->joindate;
$jobtitle = $result->jobtitle;
$city = $result->city;
$typeofsalary = $result->typeofsalary;
$contract_type = $result->contract_type;
$textout = $formality.",".$fullname.",".$sex.",".$id.",".$joindate.",".$jobtitle.",".$city.",".$typeofsalary.",".$contract_type;
}
echo $textout;
?>
But ajax dont works, only works if I put this :
$query = "SELECT * FROM dbemployeekpw WHERE email = 'camilo.uribe#kantarworldpanel.com'";
instead this:
$query = "SELECT * FROM dbemployeekpw WHERE email = '".$param."'";
But I need that the code works with second one :(
Anyone can help me with this problem ?
Thanks !!
SOLVED (works like a charm!!):
I change this:
$jinput = JFactory::getApplication()->input;
$param = $jinput->get('param', 'param', 'filter');
instead this:
$param = $_GET["param"];
and I'm still with:
$query = "SELECT * FROM dbemployeekpw WHERE email = '".$param."'";
because this code don't works for me:
$query->select($db->quoteName('*'))
->from($db->quoteName('dbemployeekpw'))
->where($db->quoteName('email') . ' = '. $db->quote($param));
Many Thanks #lodder
Before anything, lets see if the $param variable is correct and gets the value. Add the following which one the form is processed, will display the value. If the result is NULL then you firstly need to ensure you get the correct value. If you do get the correct value, then carry on reading.
Just on a side note, I would recommend looking at the following link rather than using $_GET:
http://docs.joomla.org/Retrieving_request_data_using_JInput
Lets now use up to date coding standards for you database query:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName('*'))
->from($db->quoteName('dbemployeekpw'))
->where($db->quoteName('email') . ' = '. $db->quote($param));
$db->setQuery($query);
$results = $db->loadObjectList();
Hope this helps

Get value on Request - Kendo UI Dropdownlist ASP.NET MVC

I'm searcing why the Kendo Dropdownlist box doesn't keep my value and pass it on the Request.
I have this on the chtml :
<form method="post" name="Lang">
Culture : #Culture
#(Html.Kendo().DropDownList()
.Name("cbLanguage")
.DataTextField("Name")
.DataValueField("Culture")
.BindTo(new List<Language>()
{
new Language() {Name = "Français (Canada)", Culture = "fr-CA"},
new Language() {Name = "English (Canada)", Culture = "en-CA"},
new Language() {Name = "English (United State)", Culture = "en-US"}
})
.Events(e => e
.Select("cbLanguage_select")
)
.Value(Culture)
)
<select name="lang" onchange="submitLang();">
<option></option>
<option value="en-US" #(Culture == "en-US" ? "selected=\"selected\"" : "")>English</option>
<option value="fr-CA" #(Culture == "fr-CA" ? "selected=\"selected\"" : "")>French</option>
</select>
</form>
<script>
function cbLanguage_select(e) {
$('form').submit();
};
function submitLang() {
$('form').submit();
}
</script>
After that i put this code on the _ViewStart.
if (!Request["lang"].IsEmpty())
{
Culture = UICulture = Request["lang"];
}
---- or this depend of each combo i want tested!!!!
if (!Request["cbLanguage"].IsEmpty())
{
Culture = UICulture = Request["cbLanguage"];
}
It's work really fine with the standard combo. But i never receive the value on the Request with the Kendo Dropdownlist.
I need help to find why!!!
Thank you!

Django how to chain sorting and filtering by GET request

When I select ordering I can't really include automatically per-page filter.
How do I make these filters "visible" to each other? What do I need include or read?
That's a small part of my view.py
if order == 'asc':
p = p.order_by('name')
elif order == 'desc':
p = p.order_by('-name')
elif order == 'price_asc':
p = p.order_by('price_netto')
elif order == 'price_desc':
p = p.order_by('-price_netto')
else:
p.order_by('name')
if limit == "12":
per_page = "12"
elif limit == "24":
per_page = "24"
elif limit == "48":
per_page = "48"
else:
from endless_pagination.settings import PER_PAGE
per_page = PER_PAGE
HTML
<select onchange="location = this.options[this.selectedIndex].value">
<option value="">--- Sortowanie ---</option>
<option rel="order" value="?order=desc">Malejąco według nazwy</option>
<option rel="order" value="?order=asc">Rosnąco według nazwy</option>
<option rel="order" value="?order=price_asc">Rosnąco według ceny</option>
<option rel="order" value="?order=price_desc">Malejąco według ceny</option>
</select>
Produktów na stronę:
<a rel="limit" href="?limit=12">12</a>, <a rel="limit" href="?limit=24">24</a>, <a rel="limit" href="?limit=48">48</a>
Why not use javascript, jquery. You need a function that will read the query string and override the item you're changing.
<select id="sort-dropdown">
<option value="">--- Sortowanie ---</option>
<option rel="order" value="desc">Malejąco według nazwy</option>
<option rel="order" value="asc">Rosnąco według nazwy</option>
<option rel="order" value="price_asc">Rosnąco według ceny</option>
<option rel="order" value="price_desc">Malejąco według ceny</option>
</select>
Produktów na stronę:
<a rel="limit" id="limit-12" href="#">12</a>, <a rel="limit" id="limit-24" href="#">24</a>, <a rel="limit" id="limit-48" href="#">48</a>
Then the javascript will look like:
function getParameterByName(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
function redirect(order, limit) {
window.location.url = "?order=" + order + "&limit=" + limit;
}
$("#sort-dropdown").change(function () {
redirect($(this).val(), getParameterByName("limit"));
});
$("#limit-12").change(function () {
redirect(getParameterByName("order"), "12");
});
$("#limit-24").change(function () {
redirect(getParameterByName("order"), "24");
});
$("#limit-48").change(function () {
redirect(getParameterByName("order"), "48");
});