web2py: detect change in dropdown widget - python

How can we detect a change from a dropdown widget so that code can be executed?
Table loan references table services. Both have field called interest_rate. When I change loan.service via dropdown I'd like to reflect the corresponding interest_rate from services table to loan table.
How can this be achieved?
model
db.define_table('services',
Field('service_name',requires=[IS_NOT_EMPTY(),IS_NOT_IN_DB(db,'services.service_name')]),
Field('service_type','reference service_types',requires=IS_IN_DB(db,db.service_types.id,
'%(type_name)s',
error_message='not in table',
zero=None),
ondelete='RESTRICT',
),
Field('interest_rate','decimal(15,2)',requires=IS_DECIMAL_IN_RANGE(0,100)),
Field('max_term','integer'),
auth.signature,
format='%(service_name)s',
)
db.define_table('loan',
Field('service','reference services',requires=IS_IN_DB(db,db.services.id,
'%(service_name)s',
error_message='not in table',
zero=None),
ondelete='RESTRICT',),
Field('member_id','reference members',requires=IS_IN_DB(db,db.members.id,
'%(member_name)s',
error_message='not in table',
zero=None),
ondelete='RESTRICT',
label='Member'),
Field('amount','decimal(15,2)',requires=IS_DECIMAL_IN_RANGE(1000)),
Field('interest_rate','decimal(6,2)',default=10),
)

By using javascript in the front end. For example, using jquery library:
$("select").on("change", function(){
var selected = $(this).val();
$.ajax({
url: "/get_rates",
data:{
"selected": selected
},
success: function(value_from_url){
$("div").text(value_from_url);
}
});
});

The material process is to monitor onchange with the change() event, something like this:
<script src="{{=URL('static', 'js/utils.js')}}"></script>
<script>
{{=ASSIGNJS(jslast_nos = last_nos)}}
{{=ASSIGNJS(jsaction = action)}}
jQuery(document).ready(function(){
if (jsaction == "new") {
jQuery("#AAP_doc_number").val(jslast_nos[jQuery("#AAP_pos_id").val()]);
};
jQuery("#AAP_pos_id").change(function(){
pos_id = jQuery('#AAP_pos_id').val();
jQuery("#AAP_doc_number").val(jslast_nos[pos_id]);
});
jQuery('#AAP_bags').change(function(){
jQuery("#AAP_net_kg_qty").val(Number(jQuery('#AAP_bags').val() * 50));
jQuery('#AAP_net_kg_qty').change();
});
jQuery('#AAP_net_kg_qty, #AAP_selling_price').change(function(){
n = Number(jQuery('#AAP_net_kg_qty').val()) * Number(jQuery('#AAP_selling_price').val())
jQuery('#AAP_amount').val(evenRound(Number(n),2).toFixed(2))
});
});
</script>

Related

Updating database after reordering Datatable

I'm struggling with the datatables reordering. I want when user reorder to update table in the database. For this to happen i need:
to configure the datatable to send request to the server.
send the information about reordered datatable to flask endpoint.
Process data on the backend and update database table.
I have read the documentation but it is not clear to me.
My code:
$(document).ready(function () {
var dt = $('#data').DataTable({
rowReorder: true,
dom: 'Bfrtip'
});
});
My own solution:
JavaScript code:
dt.on('row-reorder.dt', function (e, details, edit) {
var slownik = {};
for (var i = 0, ien = details.length; i < ien; i++) {
let id_asortymentu = details[i].node.id;
let nowa_pozycja = details[i].newPosition+1;
console.log(id_asortymentu);
console.log(nowa_pozycja);
slownik[id_asortymentu] = nowa_pozycja;
}
req = $.ajax({
url: 'asortymenty/tabela_reorder',
dataType: "json",
type: 'POST',
data : JSON.stringify(slownik)
});
req.done(function(data){
if (data.result == 1){
console.log('Table reordered.');
}
});
});
Flask backend code:
#admin.route('asortymenty/tabela_reorder', methods = ['GET','POST'])
def table_reorder():
slownik=request.get_json('data')
for key, value in slownik.items():
asort = Asortyment.query.get(key)
print(asort.pozycja)
asort.pozycja = value
db.session.add(asort)
db.session.commit()
return jsonify({'result' : '1'})

sending checkbox array from js to django views

I'm confused about how to do it via Ajax or Json, but how can I send the selection array (curCheck) on-click to Django views and receive it as a python array
javascript
document.getElementById('results').addEventListener('click', function(){
html_table = '<thead><tr><th>Currency</th><th>Amount</th><th>Symbol</th>><tr/><thead/>'
var checkElements = document.getElementsByClassName('ch');
for(var i =0; i< curname.length; i++){
if (checkElements[i].checked) {
var curChecked = curname[i];
var JsonArr = JSON.stringify(curChecked);
postcurChecked(JsonArr)
html_table += '<tr><td>' + curname[i] + '</td>';
}
}
document.getElementById('result_table').innerHTML = html_table;
},false;
ajax
function postsubChecked(curChecked) {
$.ajax({
"url": "http://127.0.0.1:8000/results/",
"type": "POST",
"data": {"checkbox": curChecked},
"headers": { 'X-CSRFToken': getCookie('csrftoken')}
})
}
in django
def currencyChecked(request):
body_unicode = request.body.decode('utf-8')
body_unicode = body_unicode.replace('%22','')
print(body_unicode) json_data = json.loads(body_unicode.read())
I would like to see the python array print to see it is passed to the back
but I keep getting this error:
json_data = json.loads(body_unicode.read()) AttributeError: 'str' object has no attribute 'read'
For getting the selected checkbox values and sending as an array using ajax you can use jquery like this:
consider you have multiple checkboxes and a button.
<input type="checkbox" name="imageName">
<input type="checkbox" name="imageName">
.......
<button id="deletePhoto">Delete</button>
after selecting multiple checkbox values click on this button. On clicking the below jquery will be triggered to make an arrya of selected checkbox values.
//jquery for getting the selelcted checkbox values
$(document).on("click","#deletePhoto",function(){
var favorite = [];//define array
$.each($("input[name='imageName']:checked"), function(){
favorite.push($(this).val());
});
alert("Photo Selected: " + favorite.join(", "));
if(favorite.length == 0){
alert("Select Photo to delete");
return false;
}
//ajax for deleting the multiple selelcted photos
$.ajax({type: "GET",
url: "/olx/deletePhotoFromEdit",
data:{
favorite:favorite
},
success: function(){
// put more stuff here as per your requirement
});
}
});
});
In the view you can get the array like this:
selected_photo = request.GET.getlist('favorite[]')

Add confirm when drag and drop the kanban view in odoo 10

I work with project.task model. I need to add confirmation for every stage change when user did the drag and drop. Is there any possible way.. I add validation error in write method. But Its not complete my wish. please help me
Finally I found the solution...
In this case you have to change the kanban_view.js file in web_kanban module. You can replace
add_record_to_column: function (event)
this function by this code in "kanban_view.js" file.
add_record_to_column: function (event) {
var self = this;
var column = event.target;
var record = event.data.record;
var data = {};
data[this.group_by_field] = event.target.id;
// display confirm message
if (confirm("Are you sure you want to change this stage?")){
//if click yes do this
this.dataset.write(record.id, data, {}).done(function () {
if (!self.isDestroyed()) {
self.reload_record(record);
self.resequence_column(column);
alert("You have change the stage!");
}
}).fail(this.do_reload);
}else{// if no reload the page and remain the tile in same satage
location.reload();
}},
On odoo 14, here this code:
Do search "_onAddRecordToColumn" in addons/web/static/src/js/views/kanban/kanban_controller.js
then override function (with inherited module) to this:
_onAddRecordToColumn: function (ev) {
var self = this;
var record = ev.data.record;
var column = ev.target;
if (confirm("Are you sure want to change this stage?")){
this.alive(this.model.moveRecord(record.db_id, column.db_id, this.handle))
.then(function (column_db_ids) {
return self._resequenceRecords(column.db_id, ev.data.ids)
.then(function () {
_.each(column_db_ids, function (db_id) {
var data = self.model.get(db_id);
self.renderer.updateColumn(db_id, data);
});
});
}).guardedCatch(this.reload.bind(this));
}else{
this.reload();
}
},

display data in the form of a table using Ajax

I have the below code in Ajax to display the data from python stored in MongoDB.
<script>
function f(){
$(document).ready(function(){
$.get('ajax1', function(result){
$.each(result, function(index, element) {
alert(JSON.stringify(element));
});
});
});
}
</script>
Python call for the same:
#route('/ajax1')
def func():
client = MongoClient()
db = client.collection
result = db.collection.find({},{'_id':0}).limit(2)
arr = []
for document in result:
arr.append(doc)
return (dict(items=arr))
I am getting the result as below:
[{"Name":"abc","Place":"SomePlace","Designation":"des"}]
[{"Name":"NextName","Place":"NextPlace","Designation":"Nextdes"}]
I want to print it in this format or in the form of a table:
abc Someplace des
NextName Nextplace Nextdes
Can somebody tell me how to do it? Seems simple but I am unaware of it.
Thanks!
To me it would make more sense to use the property names in the javascript as it's easier to understand and more verbose.
<script>
function f(){
$(document).ready(function(){
$.get('ajax1', function(result){
$.each(result, function(index, element) {
var row = element.Name + " " + element.Place + " " + element.Designation;
console.log(row);
});
});
});
}
</script>

flask request.args.getlist returns empty list

I am new to web development and trying to solve the following problem. My app has several checkboxes and I need to get values of checked checkboxes. Later, I use those values in further data manipulations and pass the final result using ajax. When I try:
values = request.args.getlist('check')
print values
the list is empty.
values = request.values.getlist('check')
doesn't work ether.
Flask portion:
#app.route('/smiles_to_chemfig')
def smiles_to_chemfig():
smiles_mol = request.args.get("smiles_mol")
values = request.args.getlist('check')
print values
lst = ' '.join(values)
chemfig, pdflink = smiles_mol_to_chemfig(lst,'-i direct', smiles_mol)
return jsonify(outcome = chemfig, pdf_link = pdflink)
ajax:
$(function(){
$("button#smiles").on('click', function(){
if ($('textarea[name=smiles_mol]').val()=="") {
//$("#txt_area").html("PLEASE FILL OUT THIS FIELD !")
alert("PLEASE FILL OUT THIS FIELD !");
}
else {
$.getJSON('/smiles_to_chemfig', {
smiles_mol: $('textarea[name=smiles_mol]').val()
}, function(data) {
$("#txt_area").text(data.outcome);
console.log(data.outcome);
$("#pdf").attr('src', data.pdf_link);
});
}
return false;
});
});
I suspect, that it has something to do with ajax because if I do not implement ajax everything woks good but I need to use ajax. Any suggestions and comments are highly appreciated!

Categories