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[]')
Related
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'})
I have a model that references other models, I am trying to save data using ajax
Example:
class Friend(models.Model):
name = ...
class Main(models.Model):
name = ....
friend = models.ForeignKey(Friend, on_delete=models.CASCADE)
All body comes from ajax(fetch) request
I have a table (html), and add data to cells, then with the
enter event, send data.
Like this:
input.addEventListener("keyup", function (e) {
//in this scenario I already have the whole row
// get full_row `row_data`
post_ajax = {
method: "POST",
headers: {
"X-CSRFToken": crf_token, // I get it with a regular expression
"Content-Type": "application/json",
"X-Requested-With": "XMLHttpRequest",
Accept: "application/json",
},
body: JSON.stringify(row_data),
};
fetch("my_url", post_ajax)
.then((res) => res.json())
.catch((error) => console.error("Error:", error))
.then((response) => console.log("Success:", response));
});
My view function
def save_post(request):
if request.is_ajax and request.method == "POST":
body_unicode = request.body.decode('utf-8')
data = json.loads(body_unicode)
print('here the data arrives',data)
# here the data arrives {'name': 'Ale', 'friend_id': 22}
Main.objects.create(name=data['name'], friends=data['friend_id'])
return JsonResponse({"instance": data}, status=200)
return JsonResponse({"error": ""}, status=400)
This is the error
raise TypeError("%s() got an unexpected keyword argument '%s'" %
(cls.__name__, kwarg))
TypeError: Main() got an unexpected keyword argument 'Friends'
Any idea or suggestion?
EDIT:
When you are creating the Main object, try making the "friend" attribute an object, like this:
friend = Friend.objects.get(id=data['friend_id'])
Main.objects.create(name=data['name'], friend=friend)
Also, the main issue appears to be you are calling the column "friends" but it should be "friend" when you are creating the Main object.
This:
Main.objects.create(name=data['name'], friends=data['friend_id'])
Should be:
Main.objects.create(name=data['name'], friend=data['friend_id'])
PREVIOUS ANSWER:
Assuming you are using JQuery in the template to send an AJAX request, since you did not specify.
In your urls.py:
...
path('/api/post_friend/', post_friend_api, name="post_friend_api"),
...
In your template :
<script type="text/javascript">
$("#myBurron").click(function(){
var csrfToken = $( "input[name='csrfmiddlewaretoken']"); // assuming this is a form
var friend_name = $("#friend_name").val();
$.ajax({ url: '{% url 'post_friend_api' %}',
type: "POST",
dataType: "json",
data: {'friend':friend_name, 'csrfmiddlewaretoken':csrfToken.val()},
cache: false
}).done(function(data) {
if (data.result === true){
alert(data.message);
}
});
});
});
</script>
In your views.py:
from django.http import JsonResponse
def post_friend_api(request):
data = {}
if request.POST.get('friend', None) is not None:
friend_name = request.POST.get('post_note')
# save the object and indicate success
data['result'] = True
data['message'] = "Friend saved successfully"
...
if request.is_ajax():
return JsonResponse(data)
else:
return HttpResponseBadRequest()
When you are sending data via POST don't forget to pass along your CSRF token as in the example above. This assumes you have a form on the page you can get it from, otherwise you can use something like this to get it:
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
If you don't want to deal with the CSRF token, you can mark the view with the #csrf_exempt decorator and remove the 'csrfmiddlewaretoken' data element from the Ajax call in the template, but it may not be ideal or the most secure. An example of that:
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
#csrf_exempt()
def post_note_api(request):
...
If you post more details I can update my answer.
I have a function that uses an AJAX request to fetch data from a view and returns data in the form of a list that is in the model.
In my model the data is entered with a new line character, however in my jQuery output the \n character is ignored. Can anyone help?
Data in Model object:
ankit: Hi govind!
go358938: Hi Ankit, how are you ?
Data passed as list to jquery:
{ 'list': 'ankit: Hi govind!\r\ngo358938: Hi Ankit, how are you ?' }
Data visible in Modal :
ankit: Hi govind! go358938: Hi Ankit, how are you ?
$('#chatbox').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget)
var recipient = button.data('whatever')
$.ajax({
url: "{% url 'fetcher' %}",
data: {
'search': recipient
},
dataType: 'json',
success: function (data) {
list = data.list;
$('#chatbox').find('.modal-body').html(list);
}
});
});
Views.py
def fetcher(request):
if request.is_ajax():
name = User.objects.get(username=request.GET.get('search', None))
b = ChatMessage.objects.get(user2 = name)
print(b.message)
data = {
'list': b.message,
}
return JsonResponse(data)
First, what do you mean with "jquery"-output?
Your output in the HTML as Website? Well, "\n" is not considered there as "break" but <br/>.
Your html file technically looks like this:
<div>\n
<p>Whatever</p>\n
<p>Something different</p>\n
</div>
You don't want to count every \n as <br/>.
You have two options:
Print your results inside a html element which supports \n (e.g. <pre>, <code> and <textarea> do) or replace your \n with a <br/>).
Solution 1:
<textarea class="modal-body-content">
This is a new line\nhere
</textarea>
$('#chatbox').find('.modal-body-content').html(list);
Solution 2:
$('#chatbox').find('.modal-body').html(list.replace(/\n/g, '<br/>');
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>
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>